"""
Appointment Letter Model for NGO Foundation.
Records official appointments of members, trustees, and operational officers with
statutory terms, reference tracking, and live scannable QR verification.
All code contains proper English comments for clarity and maintenance.
"""

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


class AppointmentLetter(db.Model):
    """
    Represents an officially issued Appointment Letter by the NGO Foundation.
    Contains terms of engagement, appointment date, authorized signatory credentials,
    and a unique reference code verified via the central registry.
    """
    __tablename__ = 'appointment_letters'

    id = db.Column(db.Integer, primary_key=True)

    # Unique statutory reference number (e.g., NGO/APPT/2026/0001)
    reference_no = db.Column(db.String(60), unique=True, nullable=False, index=True)

    # Foreign key linking the letter to the specific user/member account
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
    user = db.relationship('User', backref=db.backref('appointment_letters', lazy='dynamic'))

    # Snapshot of recipient contact and identification details at time of issue
    recipient_name = db.Column(db.String(100), nullable=False)
    recipient_email = db.Column(db.String(120), nullable=False)
    recipient_phone = db.Column(db.String(20), nullable=True)
    recipient_address = db.Column(db.String(255), nullable=True)

    # Official designation conferred (e.g., Senior Field Strategist, Executive Volunteer)
    designation = db.Column(db.String(100), nullable=False)

    # Key appointment milestones
    appointment_date = db.Column(db.Date, nullable=False, default=date.today)
    effective_date = db.Column(db.Date, nullable=False, default=date.today)

    # Detailed terms, duties, obligations, and code of conduct
    terms_content = db.Column(db.Text, nullable=True)

    # Authorized signatory name & executive title
    authorized_signatory = db.Column(
        db.String(120),
        default='Rajkumar Maurya, General Secretary & Trustee'
    )

    # Status of the appointment (active, probation, emeritus, revoked)
    status = db.Column(db.String(20), default='active')

    # Audit timestamps
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
    emailed_at = db.Column(db.DateTime, nullable=True)

    # Verification token for instant QR lookup
    qr_code_token = db.Column(db.String(100), nullable=True)

    @property
    def is_active(self) -> bool:
        """Checks if the appointment credential is currently in force."""
        return self.status == 'active'

    @property
    def formatted_appointment_date(self) -> str:
        """Returns standard human-readable appointment date (e.g., 19 November 2026)."""
        if self.appointment_date:
            return self.appointment_date.strftime('%d %B %Y')
        return datetime.now().strftime('%d %B %Y')

    @property
    def formatted_effective_date(self) -> str:
        """Returns standard human-readable effective commencement date."""
        if self.effective_date:
            return self.effective_date.strftime('%d %B %Y')
        return datetime.now().strftime('%d %B %Y')

    def to_dict(self) -> dict:
        """Serializes appointment record for JSON responses and logging."""
        return {
            'id': self.id,
            'reference_no': self.reference_no,
            'user_id': self.user_id,
            'recipient_name': self.recipient_name,
            'recipient_email': self.recipient_email,
            'recipient_phone': self.recipient_phone,
            'recipient_address': self.recipient_address,
            'designation': self.designation,
            'appointment_date': str(self.appointment_date),
            'effective_date': str(self.effective_date),
            'authorized_signatory': self.authorized_signatory,
            'status': self.status,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'emailed_at': self.emailed_at.isoformat() if self.emailed_at else None,
        }
