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


class ContactMessage(db.Model):
    """
    SQLAlchemy model representing Public Contact Enquiries, Visitor Inquiries,
    and Partnership Messages submitted via the /contact public portal.
    Features unique enquiry tracking references (ENQ-YYYY-XXXX), lifecycle statuses
    (unread, read/contacted, resolved), direct admin email replies, and follow-up notes.
    All code contains proper English comments for clarity and maintenance.
    """
    __tablename__ = 'contact_messages'

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

    # Unique sequential enquiry reference number (e.g. ENQ-2026-0001)
    reference_no = db.Column(db.String(50), unique=True, nullable=True, index=True)

    # Sender Contact Information
    name = db.Column(db.String(150), nullable=False)
    email = db.Column(db.String(150), nullable=False)
    phone = db.Column(db.String(50), nullable=True)

    # Message Content
    subject = db.Column(db.String(250), nullable=False)
    message = db.Column(db.Text, nullable=False)

    # Lifecycle Status: 'unread' (New), 'read' (Contacted / In Progress), 'resolved' (Closed)
    status = db.Column(db.String(50), default='unread', index=True)

    # Admin Response & Follow-up Management
    admin_reply = db.Column(db.Text, nullable=True)
    follow_up_notes = db.Column(db.Text, nullable=True)
    replied_at = db.Column(db.DateTime, nullable=True)
    replied_by_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
    replied_by = db.relationship('User', foreign_keys=[replied_by_id], backref='replied_enquiries')

    # Email Dispatch Audit
    email_sent = db.Column(db.Boolean, default=False)
    email_sent_at = db.Column(db.DateTime, nullable=True)

    # Submission & Update Timestamps
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), index=True)
    updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))

    @property
    def created_at_local(self):
        """Convert UTC submission timestamp to Indian Standard Time (IST, UTC+05:30)."""
        if not self.created_at:
            return None
        return self.created_at + timedelta(hours=5, minutes=30)

    @property
    def created_at_local_formatted(self):
        """Format IST submission time nicely (e.g. '19-Nov-2026, 03:45 PM')."""
        dt = self.created_at_local
        return dt.strftime('%d-%b-%Y, %I:%M %p') if dt else 'N/A'

    @property
    def replied_at_local(self):
        """Convert UTC reply timestamp to Indian Standard Time (IST, UTC+05:30)."""
        if not self.replied_at:
            return None
        return self.replied_at + timedelta(hours=5, minutes=30)

    @property
    def replied_at_local_formatted(self):
        """Format IST reply time nicely."""
        dt = self.replied_at_local
        return dt.strftime('%d-%b-%Y, %I:%M %p') if dt else 'N/A'

    @property
    def status_label(self):
        """Return human-readable status badge label matching specification."""
        mapping = {
            'unread': 'New / Unread',
            'read': 'In Progress / Contacted',
            'resolved': 'Resolved / Closed'
        }
        return mapping.get(self.status, self.status.capitalize())

    @property
    def status_badge_class(self):
        """Return CSS badge styling class based on enquiry status."""
        mapping = {
            'unread': 'bg-warning-subtle text-warning-emphasis border border-warning-subtle',
            'read': 'bg-info-subtle text-info-emphasis border border-info-subtle',
            'resolved': 'bg-success-subtle text-success border border-success-subtle'
        }
        return mapping.get(self.status, 'bg-secondary-subtle text-secondary')

    def __repr__(self):
        return f"<ContactMessage {self.reference_no or self.id}: {self.subject[:25]} ({self.status})>"
