from pydantic import BaseModel
from typing import Optional, List
from datetime import datetime


# ── Contacts ──────────────────────────────────────────────────────────────────

class ContactCreate(BaseModel):
    name: str
    type: str = "supplier"
    phone: Optional[str] = None
    email: Optional[str] = None
    address: Optional[str] = None
    notes: Optional[str] = None


class ContactUpdate(BaseModel):
    name: Optional[str] = None
    type: Optional[str] = None
    phone: Optional[str] = None
    email: Optional[str] = None
    address: Optional[str] = None
    notes: Optional[str] = None
    is_active: Optional[bool] = None


class ContactOut(BaseModel):
    id: int
    name: str
    type: str
    phone: Optional[str] = None
    email: Optional[str] = None
    address: Optional[str] = None
    notes: Optional[str] = None
    is_active: bool
    created_at: datetime

    model_config = {"from_attributes": True}


# ── Expenses ──────────────────────────────────────────────────────────────────

class ExpensePaymentCreate(BaseModel):
    amount: float
    notes: Optional[str] = None


class ExpensePaymentOut(BaseModel):
    id: int
    expense_id: int
    amount: float
    paid_at: datetime
    paid_by_id: int
    paid_by_name: Optional[str] = None
    notes: Optional[str] = None

    model_config = {"from_attributes": True}


class ExpenseCreate(BaseModel):
    description: str
    category: str
    contact_id: Optional[int] = None
    total_amount: float
    due_date: Optional[datetime] = None
    business_day_id: Optional[int] = None
    notes: Optional[str] = None


class ExpenseUpdate(BaseModel):
    description: Optional[str] = None
    category: Optional[str] = None
    contact_id: Optional[int] = None
    total_amount: Optional[float] = None
    due_date: Optional[datetime] = None
    notes: Optional[str] = None


class ExpenseOut(BaseModel):
    id: int
    description: str
    category: str
    contact_id: Optional[int] = None
    contact_name: Optional[str] = None
    total_amount: float
    paid_amount: float
    due_amount: float          # computed: total - paid
    status: str                # "paid" | "partial" | "due"
    due_date: Optional[datetime] = None
    business_day_id: Optional[int] = None
    created_by_id: int
    created_by_name: Optional[str] = None
    created_at: datetime
    notes: Optional[str] = None
    payments: List[ExpensePaymentOut] = []

    model_config = {"from_attributes": True}
