from datetime import datetime
from typing import Optional
from sqlalchemy import String, Text, DateTime, ForeignKey, func
from sqlalchemy.orm import Mapped, mapped_column
from app.database import Base


class Document(Base):
    __tablename__ = "documents"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    doc_type: Mapped[str] = mapped_column(String(20), nullable=False)   # bpkb | ktp | stnk | other
    location: Mapped[str] = mapped_column(String(20), default="home", nullable=False)  # bank | home | with_borrower
    status: Mapped[str] = mapped_column(String(20), default="available", nullable=False)  # available | borrowed | lost
    custodian_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
    updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now())


class BorrowRequest(Base):
    __tablename__ = "borrow_requests"

    id: Mapped[int] = mapped_column(primary_key=True)
    requester_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
    purpose: Mapped[str] = mapped_column(Text, nullable=False)
    # active | handed_over | return_pending | completed
    status: Mapped[str] = mapped_column(String(20), default="active", nullable=False)

    # Handover info (filled when custodian hands docs to recipient)
    handover_handed_by: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    handover_recipient: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    handover_date: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
    handover_photo_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)

    # Return proof (filled when borrower returns docs)
    return_handed_by: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    return_recipient: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    return_photo_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)

    completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())


class BorrowRequestItem(Base):
    __tablename__ = "borrow_request_items"

    id: Mapped[int] = mapped_column(primary_key=True)
    borrow_request_id: Mapped[int] = mapped_column(ForeignKey("borrow_requests.id", ondelete="CASCADE"), nullable=False)
    document_id: Mapped[int] = mapped_column(ForeignKey("documents.id", ondelete="RESTRICT"), nullable=False)
