from sqlalchemy import String, Text, ForeignKey, Integer, Float, Date, Time, DateTime, Boolean
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
from app.core.models.category import Category

class Employee(BaseModel):
    """
    Represents an Employee in the system's Master Data Management (MDM).
    
    The Employee model is the central profile for organizational personnel, 
    linked 1-to-1 with a system User account for authentication.
    """
    __tablename__ = 'core_employee'

    category_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('core_category.id'), nullable=True)
    full_name: Mapped[str] = mapped_column(String(100), nullable=False)
    nip: Mapped[str | None] = mapped_column(String(20), unique=True, nullable=True) # Employee ID Number

    # Linked User Account (Nullable, e.g. for field workers without system access)
    user_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('user.id'), unique=True, nullable=True)

    # Core Office & Shift Dependency
    office_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('core_office.id'), nullable=True)
    is_remote_allowed: Mapped[bool] = mapped_column(Boolean, default=False)
    
    # Specific Shift override (if null, falls back to organization-wide default)
    shift_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('hris_shift.id'), nullable=True)
    
    # HR Limits and Balances
    annual_leave_balance: Mapped[int] = mapped_column(Integer, default=12)
    reimbursement_limit: Mapped[float] = mapped_column(Float, default=5000000.0)

    # Personal Info
    email: Mapped[str | None] = mapped_column(String(120), nullable=True)
    phone: Mapped[str | None] = mapped_column(String(20), nullable=True)
    address: Mapped[str | None] = mapped_column(Text, nullable=True)

    # Job Info
    department: Mapped[str | None] = mapped_column(String(50), nullable=True)
    position: Mapped[str | None] = mapped_column(String(50), nullable=True)
    join_date: Mapped[Date | None] = mapped_column(Date, nullable=True)
    
    # Employment State (Business Logic status)
    status_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('status.id'), nullable=False)
    resign_date: Mapped[Date | None] = mapped_column(Date, nullable=True)
    
    # Active Status for Historical Archiving (Legacy/System level)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True)

    # Salary & Tax Info (Decoupled MDM fields)
    base_salary: Mapped[float] = mapped_column(Float, default=0.0)
    salary_type: Mapped[str] = mapped_column(String(20), default='monthly') # monthly, daily, hourly
    ptkp_status: Mapped[str] = mapped_column(String(20), default='TK/0', nullable=False)
    bank_name: Mapped[str | None] = mapped_column(String(50), nullable=True)
    bank_account_number: Mapped[str | None] = mapped_column(String(50), nullable=True)

    # Relationships
    category = relationship('Category')
    user = relationship('User', back_populates='employee')
    shift = relationship('Shift', backref='assigned_employees')

    @classmethod
    def query_assignable(cls):
        """
        Returns a query for employees who are eligible for assignment.
        
        Filters out soft-deleted records and employees in non-active 
        business states (e.g., resigned, terminated).
        
        Returns:
            Query: SQLAlchemy query object.
        """
        from app.core.models.status import Status
        return cls.query.join(Status, cls.status_id == Status.id).filter(
            cls.deleted_at.is_(None),
            Status.system_tag.notin_(['resigned', 'terminated', 'inactive'])
        )

    def has_transactional_data(self) -> bool:
        """
        Checks if the employee has linked transactional records in any module.
        
        This prevents accidental hard deletion of employees who have historical 
        records like attendance, payslips, or project allocations.
        
        Returns:
            bool: True if transactional data exists.
        """
        # Dynamic imports to avoid circular dependencies
        from app.modules.hris.models.employee import Attendance, Leave
        from app.modules.hris.models.payroll import Payslip, Reimbursement
        from app.modules.erp.models.core import ResourceAllocation
        
        has_attendance = Attendance.query.filter_by(employee_id=self.id).first() is not None
        has_leave = Leave.query.filter_by(employee_id=self.id).first() is not None
        has_payslip = Payslip.query.filter_by(employee_id=self.id).first() is not None
        has_reimbursement = Reimbursement.query.filter_by(employee_id=self.id).first() is not None
        has_allocation = ResourceAllocation.query.filter_by(employee_id=self.id).first() is not None
        
        return any([has_attendance, has_leave, has_payslip, has_reimbursement, has_allocation])

    @staticmethod
    def delete_employee(employee_id: str, force_hard_delete: bool = False, admin_user_id: str = None) -> dict:
        """
        Performs deletion of an employee record with dependency checks.
        
        By default, prevents deletion if transactional data exists. 
        If force_hard_delete is True, it will attempt to wipe all dependencies 
        (use with extreme caution).

        Args:
            employee_id (str): The UUID of the employee to delete.
            force_hard_delete (bool): Whether to force hard deletion. Defaults to False.
            admin_user_id (str, optional): The ID of the admin performing the force delete for logging.

        Returns:
            dict: Result payload with 'success' status and 'message'.
        """
        from app.extensions import db
        from app.core.models.user import ActivityLog
        
        employee = db.session.get(Employee, employee_id)
        if not employee:
            return {'success': False, 'message': 'Employee not found'}
            
        if employee.has_transactional_data():
            if not force_hard_delete:
                return {
                    'success': False, 
                    'message': 'Cannot delete employee with existing transaction history (Attendance, Payroll, etc). Please use Resigned status instead.'
                }
            
            # Forced hard delete path (logs the action and wipes dependencies)
            if admin_user_id:
                log = ActivityLog(
                    user_id=admin_user_id,
                    action='FORCE_DELETE_EMPLOYEE',
                    details=f'Forced hard deletion of employee {employee.full_name} ({employee.id}) and all linked history.'
                )
                db.session.add(log)
            
            # Wipe dependencies across all modules
            from app.modules.hris.models.employee import Attendance, Leave
            from app.modules.hris.models.schedule import EmployeeSchedule
            from app.modules.hris.models.payroll import Payslip, Reimbursement
            from app.modules.erp.models.core import ResourceAllocation
            
            Attendance.query.filter_by(employee_id=employee.id).delete()
            Leave.query.filter_by(employee_id=employee.id).delete()
            EmployeeSchedule.query.filter_by(employee_id=employee.id).delete()
            Payslip.query.filter_by(employee_id=employee.id).delete()
            Reimbursement.query.filter_by(employee_id=employee.id).delete()
            ResourceAllocation.query.filter_by(employee_id=employee.id).delete()
        
        db.session.delete(employee)
        db.session.commit()
        
        return {'success': True, 'message': 'Employee successfully deleted.'}

    @staticmethod
    def process_resignation(employee_id: str, resign_date: str, status_slug: str = 'resigned') -> bool:
        """
        Updates an employee's status to reflect resignation.
        
        Args:
            employee_id (str): Employee UUID.
            resign_date (str): Date of resignation (ISO string).
            status_slug (str): Slug of the 'resigned' status. Defaults to 'resigned'.

        Returns:
            bool: True if successful.
            
        Raises:
            ValueError: If employee or status slug is not found.
        """
        from app.extensions import db
        from app.core.models.status import Status

        employee = db.session.get(Employee, employee_id)
        if not employee:
            raise ValueError("Employee not found")
            
        status = Status.query.filter_by(slug=status_slug).first()
        if not status:
            raise ValueError(f"Status '{status_slug}' not found")
            
        employee.status_id = status.id
        employee.resign_date = resign_date
        db.session.commit()
        return True

    def __repr__(self):
        return f"<Employee {self.full_name}>"
