"""
Official Letterhead model for generating, archiving, printing, and emailing
official NGO letters, notices, recommendation credentials, and statutory communications.
All code contains proper English comments for clarity and maintenance.
"""

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


class OfficialLetter(db.Model):
    """
    Represents an official letter issued on NGO letterhead.
    Stores reference number, category/type, recipient contact details,
    subject, content body, authorized signatory, date, and email dispatch status.
    """
    __tablename__ = 'official_letters'

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

    # Unique reference tracking identifier (e.g., NGO/LTR/2026/0101)
    reference_no = db.Column(db.String(60), unique=True, nullable=False, index=True)

    # Classification type (e.g., General Notice, Appreciation, Permission Request, Recommendation, Authorization)
    letter_type = db.Column(db.String(100), nullable=False, default='General Notice')

    # Full name and title/designation of the recipient organization or individual
    recipient_name = db.Column(db.String(255), nullable=False)

    # Official email address of the recipient for direct electronic transmission
    recipient_email = db.Column(db.String(255), nullable=True)

    # Formal subject line of the letter
    subject = db.Column(db.String(255), nullable=False)

    # Complete text content / body paragraphs of the official letter
    content = db.Column(db.Text, nullable=False)

    # Name of the official authorized signatory (e.g., President, Secretary, Director)
    signatory_name = db.Column(db.String(150), nullable=False, default='Authorized Signatory')

    # Designation title of the signatory
    signatory_designation = db.Column(db.String(150), nullable=False, default='Secretary / Trustee')

    # Date printed on the letterhead
    letter_date = db.Column(db.Date, nullable=False, default=date.today)

    # Foreign key reference to the administrative user who authored this letter
    created_by = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='SET NULL'), nullable=True)

    # Boolean flag indicating whether the letter has been transmitted via email
    email_sent = db.Column(db.Boolean, default=False, nullable=False)

    # Timestamp when the email transmission occurred
    email_sent_at = db.Column(db.DateTime(timezone=True), nullable=True)

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

    # Relationship to user author
    author = db.relationship('User', foreign_keys=[created_by], backref=db.backref('authored_letters', lazy='dynamic'))

    def __repr__(self):
        return f"<OfficialLetter ref={self.reference_no} subject={self.subject[:30]}>"
