"""
=============================================================================
ENTERPRISE BIRTHDAY WISH & GREETING LOG MODEL
=============================================================================
Records all automated and manual birthday wishes dispatched to NGO members,
volunteers, and staff. Ensures idempotent email delivery so duplicate
greetings are not dispatched in the same calendar year.
All code contains proper English comments for clarity and maintenance.
=============================================================================
"""

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


class BirthdayWishLog(db.Model):
    """
    BirthdayWishLog table records dispatched birthday greetings,
    delivery channels, timestamp, and recipient details.
    """
    __tablename__ = 'birthday_wish_logs'

    # Primary key identifier for the greeting log entry
    id = db.Column(db.Integer, primary_key=True)

    # Foreign key referencing the recipient member/user account
    user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False)

    # Calendar year of the wish (e.g., 2026) to prevent multiple dispatches in same year
    wish_year = db.Column(db.Integer, nullable=False, index=True)

    # Exact UTC timestamp when the wish was recorded/dispatched
    sent_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)

    # Flag denoting whether the greeting email was successfully sent
    email_sent = db.Column(db.Boolean, default=False, nullable=False)

    # Snapshot of the recipient's name at the time of greeting
    recipient_name = db.Column(db.String(100), nullable=False)

    # Snapshot of the recipient's email address
    recipient_email = db.Column(db.String(120), nullable=False)

    # The personalized birthday greeting text that was dispatched
    greeting_message = db.Column(db.Text, nullable=False)

    # Dispatch channel: 'system_cron' (automated) or 'admin_manual' (manual button click)
    dispatched_by = db.Column(db.String(50), default='system_cron', nullable=False)

    # Bidirectional relationship back to User
    user = db.relationship('User', backref=db.backref('birthday_wish_history', lazy=True, cascade='all, delete-orphan'))

    @property
    def sent_at_local(self):
        """
        Converts the stored UTC timestamp to Indian Standard Time (IST: UTC+05:30)
        matching the user's local operating timezone.
        """
        if not self.sent_at:
            return None
        return self.sent_at + timedelta(hours=5, minutes=30)

    @property
    def sent_at_local_formatted(self) -> str:
        """
        Returns the formatted local time string, e.g., '02:05 PM'.
        """
        dt = self.sent_at_local
        return dt.strftime('%I:%M %p') if dt else ''

    @property
    def sent_at_local_full(self) -> str:
        """
        Returns full local date and time string, e.g., '19-Nov-2026 02:05 PM'.
        """
        dt = self.sent_at_local
        return dt.strftime('%d-%b-%Y %I:%M %p') if dt else ''

    def __repr__(self) -> str:
        """String representation of BirthdayWishLog entry."""
        return f"<BirthdayWishLog User={self.user_id} Year={self.wish_year} EmailSent={self.email_sent}>"
