from sqlalchemy import Integer, String, ForeignKey, DateTime, Boolean
from sqlalchemy.sql import func
from app.database.database import Base
from sqlalchemy.orm import Mapped, mapped_column, relationship
from typing import Optional, List


class StaffStore(Base):
    __tablename__ = "staff_stores"

    staff_id: Mapped[int] = mapped_column(ForeignKey("staff.id"), primary_key=True)
    store_id: Mapped[int] = mapped_column(
        ForeignKey("stores.store_id"), primary_key=True
    )

    assigned_at: Mapped[DateTime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), nullable=True
    )

    staff: Mapped["Staff"] = relationship("Staff", back_populates="staff_stores")
    store: Mapped["Store"] = relationship("Store", back_populates="staff_stores")


class Staff(Base):
    __tablename__ = "staff"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    username: Mapped[str] = mapped_column(
        String, index=True, nullable=False
    )
    email: Mapped[str] = mapped_column(String, unique=True, index=True, nullable=False)
    hashed_password: Mapped[str] = mapped_column(String, nullable=False)
    role_type: Mapped[str] = mapped_column(String(50), nullable=False)
    chain_id: Mapped[Optional[int]] = mapped_column(ForeignKey("chains.chain_id"), nullable=True)
    full_name: Mapped[str] = mapped_column(String, nullable=True)
    phone_number: Mapped[str] = mapped_column(String, nullable=True)
    profile_image: Mapped[str] = mapped_column(String, nullable=True)
    created_at: Mapped[DateTime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )
    updated_at: Mapped[DateTime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )
    is_deleted: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False, index=True)
    deleted_at: Mapped[Optional[DateTime]] = mapped_column(DateTime(timezone=True), nullable=True)

    staff_stores: Mapped[List["StaffStore"]] = relationship(
        "StaffStore", back_populates="staff"
    )
    employee_listings: Mapped[List["ProductListing"]] = relationship(
        "ProductListing", foreign_keys="ProductListing.employee_id"
    )
    manager_listings: Mapped[List["ProductListing"]] = relationship(
        "ProductListing", foreign_keys="ProductListing.manager_id"
    )
    manager_discounts: Mapped[List["ManagerDiscount"]] = relationship(
        "ManagerDiscount"
    )
