from sqlalchemy import String, Text, ForeignKey, Integer, Float, Date, Enum
from sqlalchemy.dialects.mysql import CHAR
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.core.models import BaseModel
from app.core.models.status import Status
from app.core.models.user import User

class Project(BaseModel):
    """
    Represents an operational Project within the organization.
    
    Projects can be standalone or converted from CRM leads. They track
    timelines, budgets, resources, and overall project health.
    """
    __tablename__ = 'erp_project'

    title: Mapped[str] = mapped_column(String(150), nullable=False)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)

    # Linked Entities
    status_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('status.id'), nullable=False)
    pm_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('user.id'), nullable=True) # Project Manager

    # Module Links
    lead_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('crm_lead.id'), nullable=True)
    contact_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('core_contact.id'), nullable=True)

    # Financials and Success Metrics
    budget: Mapped[float] = mapped_column(Float, default=0.0)
    satisfaction_score: Mapped[int | None] = mapped_column(Integer, nullable=True) # CSAT score (1-5 scale)

    # Lifecycle and Type
    project_type: Mapped[str] = mapped_column(String(20), default='standalone') # standalone, recurring
    billing_cycle: Mapped[str | None] = mapped_column(String(20), nullable=True) # monthly, yearly
    recurring_amount: Mapped[float] = mapped_column(Float, default=0.0)
    next_invoice_date: Mapped[Date | None] = mapped_column(Date, nullable=True)

    start_date: Mapped[Date] = mapped_column(Date, nullable=False)
    end_date: Mapped[Date | None] = mapped_column(Date, nullable=True)

    # Relationships
    status = relationship('Status')
    pm = relationship('User')
    lead = relationship('Lead') # CRM cross-link
    contact = relationship('Contact') # CRM cross-link
    invoices = relationship('Invoice', back_populates='project', cascade="all, delete-orphan")
    expenses = relationship('Expense', back_populates='project')
    
    @property
    def tasks(self):
        """
        Retrieves all active (non-deleted) tasks associated with this project.
        Note: Accessing this in a loop may cause N+1 query overhead.
        """
        from app.core.models.task import Task
        return Task.query.filter_by(entity_type='project', entity_id=self.id, deleted_at=None).all()

    def __repr__(self):
        return f"<Project {self.title}>"

class Invoice(BaseModel):
    """
    Represents an Accounts Receivable record (Money In).
    
    Tracks billing milestones and maintains a simple ledger of partial 
    payments for cashflow visibility.
    """
    __tablename__ = 'erp_invoice'

    number: Mapped[str] = mapped_column(String(50), unique=True, nullable=False) # e.g., INV-2024-001

    project_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('erp_project.id'), nullable=True)
    contact_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('core_contact.id'), nullable=False)

    status_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('status.id'), nullable=False)

    issue_date: Mapped[Date] = mapped_column(Date, nullable=False)
    due_date: Mapped[Date] = mapped_column(Date, nullable=False)

    amount: Mapped[float] = mapped_column(Float, default=0.0)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)

    # Payment Metrics
    paid_amount: Mapped[float] = mapped_column(Float, default=0.0)

    # Relationships
    project = relationship('Project', back_populates='invoices')
    contact = relationship('Contact')
    status = relationship('Status')
    payments = relationship('InvoicePayment', back_populates='invoice', cascade="all, delete-orphan", order_by="desc(InvoicePayment.date)")

    @property
    def balance_due(self) -> float:
        """Calculates the remaining unpaid balance for this invoice."""
        return max(0, self.amount - self.paid_amount)

    def __repr__(self):
        return f"<Invoice {self.number}>"

class InvoicePayment(BaseModel):
    """
    Represents an individual payment transaction linked to an Invoice.
    
    Allows tracking of multiple installments or partial payments.
    """
    __tablename__ = 'erp_invoice_payment'

    invoice_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('erp_invoice.id'), nullable=False)
    amount: Mapped[float] = mapped_column(Float, nullable=False)
    date: Mapped[Date] = mapped_column(Date, nullable=False)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    
    recorded_by_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('user.id'), nullable=False)

    # Relationships
    invoice = relationship('Invoice', back_populates='payments')
    recorded_by = relationship('User')

    def __repr__(self):
        return f"<InvoicePayment {self.amount} on {self.date}>"

class Expense(BaseModel):
    """
    Represents an Accounts Payable or general Cash-Out log.
    
    Used for tracking operational costs. Can be linked to projects for 
    profitability analysis or originate from employee reimbursements.
    """
    __tablename__ = 'erp_expense'

    title: Mapped[str] = mapped_column(String(100), nullable=False)
    amount: Mapped[float] = mapped_column(Float, default=0.0)
    date: Mapped[Date] = mapped_column(Date, nullable=False)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)

    # Status: pending, paid, cancelled
    status: Mapped[str] = mapped_column(String(20), server_default='pending', default='pending', nullable=False)

    # Category tagging: travel, utilities, salaries, reimbursement, etc.
    category: Mapped[str] = mapped_column(String(30), default='other', nullable=False)

    # Integration Links
    project_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('erp_project.id'), nullable=True)
    user_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('user.id'), nullable=False) # PIC

    # Source Tracking (Traceability)
    source: Mapped[str | None] = mapped_column(String(30), nullable=True) # e.g., 'reimbursement'
    source_id: Mapped[str | None] = mapped_column(CHAR(36), nullable=True) # FK to source entity

    receipt_file: Mapped[str | None] = mapped_column(String(255), nullable=True)

    # Relationships
    project = relationship('Project', back_populates='expenses')
    user = relationship('User')

    def __repr__(self):
        return f"<Expense {self.title} - {self.amount}>"

class ResourceAllocation(BaseModel):
    """
    Manages Employee utilization across projects.
    
    Used for capacity planning and workforce management within project timelines.
    """
    __tablename__ = 'erp_resource_allocation'

    project_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('erp_project.id'), nullable=False)
    task_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('core_task.id'), nullable=True)
    employee_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('core_employee.id'), nullable=False)

    start_date: Mapped[Date] = mapped_column(Date, nullable=False)
    end_date: Mapped[Date] = mapped_column(Date, nullable=False)

    # Target capacity (e.g., 100 = full-time dedication, 20 = part-time)
    allocation_percentage: Mapped[int] = mapped_column(Integer, default=100)
    
    # Relationships
    project = relationship('Project', backref='allocations')
    employee = relationship('Employee')

    def __repr__(self):
        return f"<ResourceAllocation {self.employee_id} -> {self.project_id}>"
