"""
Fiscal Period model for General Ledger period management.
"""
from sqlalchemy import Column, Integer, String, DateTime, Enum, Boolean, Index
from sqlalchemy.orm import relationship
from datetime import datetime
import enum
from ...shared.config.database import Base


class PeriodStatus(str, enum.Enum):
    """Status of a fiscal period."""
    open = 'open'
    closed = 'closed'
    locked = 'locked'  # Locked periods cannot be modified


class FiscalPeriod(Base):
    """Fiscal Period for organizing financial transactions."""
    __tablename__ = 'fiscal_periods'
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    
    # Period identification
    period_name = Column(String(50), unique=True, nullable=False, index=True)  # e.g., "2024-Q1", "2024-01"
    period_type = Column(String(20), nullable=False)  # 'monthly', 'quarterly', 'yearly'
    
    # Period dates
    start_date = Column(DateTime, nullable=False, index=True)
    end_date = Column(DateTime, nullable=False, index=True)
    
    # Period status
    status = Column(Enum(PeriodStatus), default=PeriodStatus.open, nullable=False, index=True)
    is_current = Column(Boolean, default=False, nullable=False, index=True)  # Only one current period
    
    # Period metadata
    closed_by = Column(Integer, nullable=True)  # User ID who closed the period
    closed_at = Column(DateTime, nullable=True)
    notes = Column(String(500), nullable=True)
    
    # Timestamps
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    
    # Relationships
    journal_entries = relationship('JournalEntry', back_populates='fiscal_period')
    
    # Indexes
    __table_args__ = (
        Index('idx_fiscal_period_dates', 'start_date', 'end_date'),
        Index('idx_fiscal_period_status', 'status', 'is_current'),
    )

