"""Local model linking portal users to MyFatoorah suppliers."""

from django.conf import settings
from django.db import models

from apps.core.models import TimeStampedModel


class SupplierProfile(TimeStampedModel):
    """One-to-one mapping between a portal user and a MyFatoorah supplier.

    The single source of truth for supplier data is MyFatoorah; we only store
    the link. Every portal request fetches live data via the client.
    """

    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="supplier_profile",
    )
    supplier_code = models.PositiveIntegerField(
        unique=True,
        help_text="MyFatoorah SupplierCode (the integer assigned by MyFatoorah).",
    )

    class Meta:
        db_table = "supplier_profiles"
        verbose_name = "Supplier profile"
        verbose_name_plural = "Supplier profiles"

    def __str__(self) -> str:
        return f"{self.user} → MF#{self.supplier_code}"


class SupplierTransaction(TimeStampedModel):
    """Tracks invoices created by a supplier.

    MyFatoorah has no "list invoices" API, so we only persist the InvoiceId
    (plus the supplier link) when an invoice is created via SendPayment.
    All transaction details are fetched live from GetPaymentStatus when
    listing — there is no need to duplicate that data locally.
    """

    supplier = models.ForeignKey(
        SupplierProfile,
        on_delete=models.CASCADE,
        related_name="transactions",
    )
    invoice_id = models.CharField(
        max_length=64,
        unique=True,
        help_text="MyFatoorah InvoiceId returned by SendPayment.",
    )
    notified_at = models.DateTimeField(
        null=True,
        blank=True,
        help_text="Set once a payment-success email has been sent for this invoice.",
    )

    class Meta:
        db_table = "supplier_transactions"
        verbose_name = "Supplier transaction"
        verbose_name_plural = "Supplier transactions"
        ordering = ("-created_at",)

    def __str__(self) -> str:
        return f"INV#{self.invoice_id}"

