from typing import Optional
from datetime import datetime
from pydantic import Field
from sqlalchemy import DateTime, Float, ForeignKey, Integer, String
from sqlalchemy.orm import Mapped, mapped_column, Session, relationship
from app.models.main import Base
from app.utils.schemas_utils import CustomModel

class PaymentBase(CustomModel):
    date: datetime
    simulation_code: str
    order_number: str
    count: int
    amount: float
    action: Optional[str] = Field(default=None)

class TblPayment(Base):
    __tablename__ = "tbl_payment"

    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
    date: Mapped[datetime] = mapped_column("end_date", DateTime, nullable=True)
    simulation_code: Mapped[str] = mapped_column(String(100), ForeignKey("tbl_simulation.simulation_code"), nullable=False)
    order_number: Mapped[str] = mapped_column(String(100), nullable=False)
    count: Mapped[int] = mapped_column(Integer, nullable=False)
    amount: Mapped[float] = mapped_column(Float, nullable=False)
    action: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)

    simulation = relationship("TblSimulation", back_populates="payments")

    @classmethod
    def create(cls, data: PaymentBase, db: Session) -> "TblPayment":
        new_payment = cls(**data.model_dump())
        db.add(new_payment)
        db.flush()
        return new_payment
