from sqlalchemy import Column, Integer, String, Boolean, DateTime, Float, ForeignKey, Text
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from database import Base


def _utcnow():
    return datetime.now(timezone.utc)


class Contact(Base):
    __tablename__ = "contacts"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, nullable=False)
    type = Column(String, default="supplier", nullable=False)  # supplier|staff|utility|other
    phone = Column(String, nullable=True)
    email = Column(String, nullable=True)
    address = Column(Text, nullable=True)
    notes = Column(Text, nullable=True)
    is_active = Column(Boolean, default=True, nullable=False)
    created_at = Column(DateTime(timezone=True), default=_utcnow)

    expenses = relationship("Expense", back_populates="contact")


class Expense(Base):
    __tablename__ = "expenses"

    id = Column(Integer, primary_key=True, index=True)
    description = Column(String, nullable=False)
    category = Column(String, nullable=False)  # supplier|utilities|rent|maintenance|staff|equipment|other
    contact_id = Column(Integer, ForeignKey("contacts.id"), nullable=True)
    total_amount = Column(Float, nullable=False)
    paid_amount = Column(Float, default=0.0, nullable=False)
    due_date = Column(DateTime(timezone=True), nullable=True)
    business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True)
    created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    created_at = Column(DateTime(timezone=True), default=_utcnow)
    notes = Column(Text, nullable=True)

    contact = relationship("Contact", back_populates="expenses")
    created_by = relationship("User", foreign_keys=[created_by_id])
    payments = relationship("ExpensePayment", back_populates="expense", cascade="all, delete-orphan")


class ExpensePayment(Base):
    __tablename__ = "expense_payments"

    id = Column(Integer, primary_key=True, index=True)
    expense_id = Column(Integer, ForeignKey("expenses.id"), nullable=False)
    amount = Column(Float, nullable=False)
    paid_at = Column(DateTime(timezone=True), default=_utcnow)
    paid_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    notes = Column(Text, nullable=True)

    expense = relationship("Expense", back_populates="payments")
    paid_by = relationship("User", foreign_keys=[paid_by_id])
