"""
Chart of Accounts model for General Ledger.
"""
from sqlalchemy import Column, Integer, String, DateTime, Enum, ForeignKey, Text, Index
from sqlalchemy.orm import relationship
from datetime import datetime
import enum
from ...shared.config.database import Base


class AccountType(str, enum.Enum):
    """Types of accounts in the chart of accounts."""
    asset = 'asset'
    liability = 'liability'
    equity = 'equity'
    revenue = 'revenue'
    expense = 'expense'
    cogs = 'cogs'  # Cost of Goods Sold


class AccountCategory(str, enum.Enum):
    """Categories for organizing accounts."""
    # Assets
    current_assets = 'current_assets'
    fixed_assets = 'fixed_assets'
    # Liabilities
    current_liabilities = 'current_liabilities'
    long_term_liabilities = 'long_term_liabilities'
    # Equity
    equity = 'equity'
    retained_earnings = 'retained_earnings'
    # Revenue
    operating_revenue = 'operating_revenue'
    other_revenue = 'other_revenue'
    # Expenses
    operating_expenses = 'operating_expenses'
    cogs = 'cogs'
    other_expenses = 'other_expenses'


class ChartOfAccounts(Base):
    """Chart of Accounts for General Ledger."""
    __tablename__ = 'chart_of_accounts'
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    
    # Account identification
    account_code = Column(String(20), unique=True, nullable=False, index=True)
    account_name = Column(String(255), nullable=False)
    account_type = Column(Enum(AccountType), nullable=False, index=True)
    account_category = Column(Enum(AccountCategory), nullable=True, index=True)
    
    # Account details
    description = Column(Text, nullable=True)
    parent_account_id = Column(Integer, ForeignKey('chart_of_accounts.id'), nullable=True)
    is_active = Column(String(10), default='true', nullable=False)  # Using string for compatibility
    
    # Metadata
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    
    # Relationships
    parent_account = relationship('ChartOfAccounts', remote_side=[id], backref='child_accounts')
    journal_lines = relationship('JournalLine', back_populates='account')
    
    # Indexes
    __table_args__ = (
        Index('idx_chart_of_accounts_type', 'account_type', 'is_active'),
        Index('idx_chart_of_accounts_category', 'account_category', 'is_active'),
    )

