"""
Expense model for official NGO operational expense tracking, category audits,
bill receipt vouchers, and treasury reconciliation.
All code contains proper English comments for clarity and maintenance.
"""

from datetime import date, datetime, timezone
from app.extensions import db


class Expense(db.Model):
    """
    Represents an official expense voucher incurred by the NGO.
    Stores voucher number, category, monetary amount, purpose, vendor details,
    payment method, attached bill file, audit approval status, and timestamps.
    """
    __tablename__ = 'expenses'

    # Primary key identifier
    id = db.Column(db.Integer, primary_key=True)

    # Unique expense voucher reference code (e.g., VOUCH-2026-001)
    voucher_no = db.Column(db.String(50), unique=True, nullable=False, index=True)

    # Expense classification category (e.g., Travel, Events, Utilities, Staff, Office, Project Expense)
    category = db.Column(db.String(100), nullable=False, index=True)

    # Monetary value in INR currency
    amount = db.Column(db.Numeric(12, 2), nullable=False)

    # Date when the expense was actually incurred
    expense_date = db.Column(db.Date, nullable=False, default=date.today)

    # Detailed justification or explanation of the expenditure
    purpose = db.Column(db.Text, nullable=False)

    # Name of the vendor, shop, contractor, or beneficiary service provider
    vendor_name = db.Column(db.String(150), nullable=True)

    # Payment settlement mode (Cash, Bank Transfer, UPI, Cheque, Card)
    payment_mode = db.Column(db.String(50), nullable=False, default='Cash')

    # Path or filename of the uploaded bill, tax invoice, or receipt document
    bill_file = db.Column(db.String(255), nullable=True)

    # Foreign key link to the administrative or finance user who recorded this voucher
    recorded_by = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='SET NULL'), nullable=True)

    # Official verification and scrutiny status ('Approved', 'Pending Audit', 'Audited')
    status = db.Column(db.String(50), nullable=False, default='Approved')

    # Additional notes or internal remarks
    notes = db.Column(db.Text, nullable=True)

    # Automatic UTC creation timestamp
    created_at = db.Column(db.DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)

    # Relationship to user who recorded the expense
    recorder = db.relationship('User', foreign_keys=[recorded_by], backref=db.backref('recorded_expenses', lazy='dynamic'))

    def __repr__(self):
        return f"<Expense voucher={self.voucher_no} amount={self.amount} category={self.category}>"
