"""
Issued Certificate Model for NGO Foundation.
Stores comprehensive details of certificates generated by administrators for
members, volunteers, and activity participants, including the selected template,
course or programme name, certificate number, and verification metadata.
All code contains proper English comments for clarity and maintenance.
"""

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


class IssuedCertificate(db.Model):
    """
    SQLAlchemy model representing an officially issued certificate.
    Tracks recipient details, programme/course information, the chosen visual template,
    and unique identification numbers for verification and auditing.
    """

    # Database table name
    __tablename__ = 'issued_certificates'

    # Primary Key: Unique autoincrementing record ID
    id = db.Column(db.Integer, primary_key=True)

    # Unique public Certificate Number (e.g., CERT-2026-0001) used for verification
    certificate_no = db.Column(db.String(64), unique=True, nullable=False, index=True)

    # Recipient Personal Details
    recipient_name = db.Column(db.String(120), nullable=False)
    recipient_email = db.Column(db.String(120), nullable=True)
    recipient_phone = db.Column(db.String(30), nullable=True)

    # Member / Registration Code (e.g., NGO-2026-0006)
    member_code = db.Column(db.String(50), nullable=True, index=True)

    # Optional foreign keys linking to existing User or VolunteerApplication records
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
    volunteer_app_id = db.Column(db.Integer, db.ForeignKey('volunteer_applications.id'), nullable=True)

    # Course / Program details specified during certificate generation
    program_name = db.Column(db.String(255), nullable=False)
    certificate_type = db.Column(db.String(100), default='Achievement', nullable=False)

    # Selected Visual Template Identifier: template_1 through template_6
    template_id = db.Column(db.String(30), default='template_1', nullable=False)

    # Official Date of Issuance (defaults to current UTC time)
    issue_date = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)

    # Certificate lifecycle status: 'active' or 'revoked'
    status = db.Column(db.String(20), default='active', nullable=False)

    # Base64 data URI or URL of the verification QR Code
    qr_code_data = db.Column(db.Text, nullable=True)

    # Foreign Key: Admin user account that generated this certificate
    created_by_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)

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

    # Optional internal administrative notes
    notes = db.Column(db.Text, nullable=True)

    # Relationships
    user = db.relationship('User', foreign_keys=[user_id], backref='issued_certificates', lazy=True)
    created_by = db.relationship('User', foreign_keys=[created_by_id], lazy=True)
    volunteer_app = db.relationship('VolunteerApplication', foreign_keys=[volunteer_app_id], lazy=True)

    def to_dict(self):
        """
        Serializes the certificate record into a dictionary format
        suitable for JSON API responses and AJAX handlers.
        """
        return {
            'id': self.id,
            'certificate_no': self.certificate_no,
            'recipient_name': self.recipient_name,
            'recipient_email': self.recipient_email or '',
            'recipient_phone': self.recipient_phone or '',
            'member_code': self.member_code or '',
            'program_name': self.program_name,
            'certificate_type': self.certificate_type,
            'template_id': self.template_id,
            'issue_date': self.issue_date.strftime('%d %b %Y') if self.issue_date else '',
            'status': self.status,
            'qr_code_data': self.qr_code_data or '',
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else '',
        }

    def __repr__(self) -> str:
        """String representation of IssuedCertificate."""
        return f"<IssuedCertificate {self.certificate_no} for {self.recipient_name} ({self.template_id})>"
