# @File: backend/models/shipment_notifications.py
# @Desc: Delivery log for DHL shipment status-change email notifications.
#        Every outbound email (or attempted email) produces exactly one row
#        here, regardless of SMTP success/failure, so admins can audit:
#
#          - which customer was notified
#          - what status transition triggered the email
#          - whether SMTP actually delivered the message
#
#        The table is queried from the admin CMS under
#        "Shipping → DHL Notifications" and is used by the notification
#        service to avoid sending duplicate emails for the same status.
from datetime import datetime

from core.database import Base
from sqlalchemy import Boolean, Column, DateTime, Integer, String, Text


class ShipmentNotification(Base):
    """One persisted email notification for a DHL tracking status change."""

    __tablename__ = "shipment_notifications"
    __table_args__ = {"extend_existing": True}

    id = Column(Integer, primary_key=True, index=True, autoincrement=True, nullable=False)

    # Which order / shipment this notification belongs to.
    order_id = Column(Integer, nullable=True, index=True)
    order_number = Column(String(128), nullable=True)
    tracking_number = Column(String(128), nullable=False, index=True)

    # Who we tried to email.
    recipient_email = Column(String(255), nullable=False)

    # Status transition that triggered this email.
    previous_status = Column(String(64), nullable=True)
    new_status = Column(String(64), nullable=False)

    # Human-readable latest event copied from the DHL response so the admin
    # UI can show context without re-fetching.
    event_description = Column(Text, nullable=True)
    event_location = Column(String(255), nullable=True)
    event_timestamp = Column(String(64), nullable=True)

    # SMTP outcome.
    success = Column(Boolean, nullable=False, default=False)
    error_message = Column(Text, nullable=True)

    # Whether the email was sourced from stubbed tracking data (no DHL
    # credentials configured). Useful so demo notifications are obvious in
    # the admin log.
    stub = Column(Boolean, nullable=False, default=False)

    created_at = Column(DateTime(timezone=True), default=datetime.now, nullable=False)