from django.core.exceptions import ValidationError
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
import uuid
from django.contrib.auth.models import User
from django_icon_picker.field import IconField
from django.contrib.auth import get_user_model
from ckeditor.fields import RichTextField


User = get_user_model()

class Catalog(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, unique=True)
    description = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

class Category(models.Model):
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)

    class Meta:
        # The name displayed for a single item
        verbose_name = "Genre"
        
        # The name displayed in the sidebar (plural)
        verbose_name_plural = "Genres"

    def __str__(self):
        return self.name

class PaymentDetailsMixin(models.Model):
    """
    Shared payment-method fields for Author and AuthorApplication, kept as
    an abstract mixin so the two stay in lockstep — approve_application()
    copies these verbatim from the application onto the new Author.

    Four distinct payment methods, each with only the fields that method
    actually needs (not one generic "account number" field pretending to
    cover all of them):
      - Bank Transfer:        bank_name, account number, branch (+code),
                               account type, plus optional international
                               transfer fields.
      - M-Pesa Send Money:    payment_phone (the number money is sent to) +
                               payment_account_name (registered name).
      - M-Pesa PayBill:       paybill_number + paybill_account_number.
      - M-Pesa Till:          till_number.
    payment_account_name / payment_reference / payment_phone / payment_email
    are shared across all four, meaning what they represent (e.g. "account
    holder name" vs "M-Pesa registered name" vs "registered business name")
    depends on payment_method.
    """
    PAYMENT_BANK          = "bank"
    PAYMENT_MPESA_SEND    = "mpesa_send"
    PAYMENT_MPESA_PAYBILL = "mpesa_paybill"
    PAYMENT_MPESA_TILL    = "mpesa_till"
    PAYMENT_METHODS = [
        (PAYMENT_BANK,          "Bank Transfer"),
        (PAYMENT_MPESA_SEND,    "M-Pesa — Send Money"),
        (PAYMENT_MPESA_PAYBILL, "M-Pesa — PayBill"),
        (PAYMENT_MPESA_TILL,    "M-Pesa — Till / Buy Goods"),
    ]
    ACCOUNT_SAVINGS = "savings"
    ACCOUNT_CURRENT = "current"
    ACCOUNT_TYPES = [(ACCOUNT_SAVINGS, "Savings"), (ACCOUNT_CURRENT, "Current")]

    payment_method = models.CharField(max_length=20, choices=PAYMENT_METHODS, blank=True)
    payment_account_name = models.CharField(
        max_length=255, blank=True,
        help_text="Account holder name (Bank) / registered name (M-Pesa Send Money) / "
                   "registered business name (PayBill, Till).",
    )
    payment_reference = models.CharField(max_length=100, blank=True, help_text="Reference/narration to include with payments.")
    payment_phone      = models.CharField(
        max_length=20, blank=True,
        help_text="Required for M-Pesa Send Money (the number money is sent to); optional contact number otherwise.",
    )
    payment_email = models.EmailField(blank=True, help_text="Optional — used for payment notifications.")
    payment_details_confirmed = models.BooleanField(
        default=False,
        help_text="Applicant confirmed these details are correct and belong to them / their authorized business.",
    )

    # Bank Transfer
    bank_name           = models.CharField(max_length=255, blank=True)
    bank_account_number = models.CharField(max_length=50, blank=True)
    bank_branch         = models.CharField(max_length=255, blank=True)
    bank_branch_code    = models.CharField(max_length=20, blank=True)
    bank_account_type   = models.CharField(max_length=10, choices=ACCOUNT_TYPES, blank=True)
    # International bank transfer — optional, only relevant for cross-border payment
    bank_swift_code           = models.CharField(max_length=20, blank=True)
    bank_address              = models.TextField(blank=True)
    recipient_address         = models.TextField(blank=True)
    payment_currency          = models.CharField(max_length=10, blank=True, default="KES")
    intermediary_bank_details = models.TextField(blank=True)

    # M-Pesa PayBill
    paybill_number         = models.CharField(max_length=20, blank=True)
    paybill_account_number = models.CharField(max_length=100, blank=True)

    # M-Pesa Till / Buy Goods
    till_number = models.CharField(max_length=20, blank=True)

    class Meta:
        abstract = True


class Author(PaymentDetailsMixin, models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(
        max_length=300, unique=True, blank=True, null=True,
        help_text="URL-friendly identifier, auto-generated from the name if left blank.",
    )
    bio = models.TextField(blank=True, null=True)
    image = models.ImageField(upload_to='author_images/', blank=True, null=True)
    email = models.EmailField(blank=True, help_text="Used to send earnings statements directly to the author.")
    address = models.TextField(blank=True, help_text="Party address for the Distribution & Consignment Agreement.")
    id_number = models.CharField(
        max_length=100, blank=True,
        help_text="National ID / passport number, or company registration number for a legal entity.",
    )
    default_my_keep_percent = models.DecimalField(
        max_digits=5, decimal_places=2, default=30.00,
        help_text="Default Tai AfroPress margin % applied to all books by this author.",
    )

    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = self._generate_unique_slug()
        super().save(*args, **kwargs)

    def _generate_unique_slug(self):
        base = slugify(self.name)[:290] or "author"
        slug = base
        suffix = 2
        while Author.objects.filter(slug=slug).exclude(pk=self.pk).exists():
            slug = f"{base}-{suffix}"
            suffix += 1
        return slug

class Publisher(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField(blank=True, help_text="Used to send monthly distribution statements.")
    default_my_keep_percent = models.DecimalField(
        max_digits=5, decimal_places=2, default=25.00,
        help_text="Default Tai AfroPress margin % applied to all books from this publisher.",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name


class DistributionPackage(models.Model):
    """
    An editable distribution tier authors choose when applying (e.g.
    Bronze/Silver/Gold/Platinum). my_keep_percent sets Author.default_my_keep_percent
    on approval; the other fields describe what the tier includes and drive
    the public offerings page copy.
    """
    name = models.CharField(max_length=100, unique=True, help_text="e.g. Bronze, Silver, Gold, Platinum")
    tier = models.PositiveIntegerField(unique=True, help_text="Display order — lower shows first (Bronze=1, Silver=2, ...).")
    description = models.TextField(blank=True, help_text="Shown to authors on the distribution offerings page.")
    my_keep_percent = models.DecimalField(
        max_digits=5, decimal_places=2,
        help_text="Tai AfroPress's keep % on Tai Bookstore / website sales — the author gets "
                   "the remainder, fixed to the price they agreed regardless of any markup.",
    )
    allows_external_bookstores = models.BooleanField(
        default=False,
        help_text="Whether this package includes distribution beyond Tai Bookstore.",
    )
    external_bookstore_author_percent = models.DecimalField(
        max_digits=5, decimal_places=2, null=True, blank=True,
        help_text="Author's % of the agreed price on sales through EXTERNAL bookstores "
                   "(independent of my_keep_percent, which only governs Tai/website sales). "
                   "The bookstore's own cut comes out of the actual sale amount separately; "
                   "Tai AfroPress keeps whatever's left. Irrelevant if external bookstores "
                   "aren't allowed for this package.",
    )
    book_signings_included = models.PositiveIntegerField(
        default=0, help_text="Number of book signings included per year.",
    )
    includes_social_media_management = models.BooleanField(
        default=False, verbose_name="Includes social media promotion",
    )
    is_featured = models.BooleanField(
        default=False,
        help_text="Highlight this package as \"Most Popular\" on the public offerings page.",
    )
    is_active = models.BooleanField(
        default=True,
        help_text="Inactive packages are hidden from the public offerings page and can't be "
                   "chosen for new applications. Existing authors/applications on a "
                   "deactivated package are unaffected.",
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["tier"]
        verbose_name = "Distribution Package"
        verbose_name_plural = "Distribution Packages"

    def __str__(self):
        return self.name

    def clean(self):
        super().clean()
        if self.allows_external_bookstores and self.external_bookstore_author_percent is None:
            raise ValidationError({
                'external_bookstore_author_percent': "Required when external bookstore distribution is allowed.",
            })


class AuthorApplication(PaymentDetailsMixin, models.Model):
    """
    A prospective author's self-service distribution application: package
    choice, signed agreement, profile/payment details, and the book(s) they
    want distributed. Nothing here becomes a real Author/Book until an admin
    approves it (see catalog_app/services/author_application_service.py) —
    mirrors the PendingInventoryTransaction maker-checker pattern.
    """
    STATUS_PENDING  = "pending_review"
    STATUS_APPROVED = "approved"
    STATUS_REJECTED = "rejected"
    STATUSES = [
        (STATUS_PENDING,  "Pending Review"),
        (STATUS_APPROVED, "Approved"),
        (STATUS_REJECTED, "Rejected"),
    ]

    package = models.ForeignKey(DistributionPackage, on_delete=models.PROTECT, related_name="applications")

    # Profile
    full_name = models.CharField(max_length=255)
    email     = models.EmailField()
    phone     = models.CharField(max_length=20, blank=True)
    bio       = models.TextField(blank=True)
    address   = models.TextField(blank=True, help_text="Party address for the Distribution & Consignment Agreement.")
    id_number = models.CharField(
        max_length=100, blank=True,
        help_text="National ID / passport number, or company registration number for a legal entity.",
    )

    # Payment details fields come from PaymentDetailsMixin — sensitive,
    # admin visibility is restricted to finance staff (see admin.py).

    # Signature / proof of agreement
    agreement_text_snapshot = models.TextField(
        help_text="Exact terms text shown to the applicant at signing time — kept even if "
                   "the live agreement template is edited later.",
    )
    signed_name        = models.CharField(max_length=255, help_text="Full name typed by the applicant as their signature.")
    signed_at           = models.DateTimeField()
    signed_ip_address  = models.GenericIPAddressField(null=True, blank=True)

    # Review
    status          = models.CharField(max_length=20, choices=STATUSES, default=STATUS_PENDING, db_index=True)
    reviewed_by     = models.ForeignKey(
        User, on_delete=models.SET_NULL, null=True, blank=True, related_name="reviewed_author_applications",
    )
    reviewed_at      = models.DateTimeField(null=True, blank=True)
    rejection_reason = models.TextField(blank=True)

    # What was actually created on approval
    created_author = models.ForeignKey(
        Author, on_delete=models.SET_NULL, null=True, blank=True, related_name="applications",
    )

    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]
        verbose_name = "Author Application"
        verbose_name_plural = "Author Applications"

    def __str__(self):
        return f"{self.full_name} | {self.package.name} | {self.get_status_display()}"


class AuthorApplicationBook(models.Model):
    application = models.ForeignKey(AuthorApplication, on_delete=models.CASCADE, related_name="books")
    title             = models.CharField(max_length=512)
    isbn              = models.CharField(max_length=50, blank=True)
    category          = models.ForeignKey(
        Category, on_delete=models.SET_NULL, null=True, blank=True, related_name="+",
    )
    catalog           = models.ForeignKey(
        Catalog, on_delete=models.SET_NULL, null=True, blank=True, related_name="+",
        help_text="Which storefront collection this book belongs in — set by staff during "
                   "review; required before the application can be approved.",
    )
    description       = models.TextField(blank=True)
    cover             = models.ImageField(upload_to="author_application_covers/", blank=True, null=True)
    publication_year  = models.IntegerField(null=True, blank=True)
    selling_price_kes = models.DecimalField(max_digits=10, decimal_places=2)
    copies_to_deliver = models.PositiveIntegerField(
        default=10,
        help_text="Number of physical copies the author will supply to Tai AfroPress for "
                   "distribution. Informational at application stage — actual stock is only "
                   "created later when those copies physically arrive and are received "
                   "through the normal Receive Stock approval flow.",
    )

    created_book = models.ForeignKey(
        "Book", on_delete=models.SET_NULL, null=True, blank=True, related_name="+",
    )

    class Meta:
        verbose_name = "Submitted Book"
        verbose_name_plural = "Submitted Books"

    def __str__(self):
        return self.title


class LegacyAuthorInvitation(PaymentDetailsMixin, models.Model):
    """
    Retroactively bring an author + their already-catalogued books (uploaded
    by staff before the self-service application flow existed) under a
    signed Distribution & Consignment Agreement — without creating
    duplicate Author/Book rows the way AuthorApplication does.

    Staff picks the existing Author and existing Book(s) to cover, then
    sends an emailed link (token-based, no author login exists) that lets
    the author pick a package, fill in whatever's missing on their profile/
    payment details, preview, and sign — same agreement machinery as
    AuthorApplication, just pointed at existing rows instead of new ones.
    Nothing on the existing Author/Book rows changes until admin approval
    (see catalog_app/services/legacy_invitation_service.py).
    """
    STATUS_DRAFT     = "draft"
    STATUS_SENT      = "sent"
    STATUS_SUBMITTED = "submitted"
    STATUS_APPROVED  = "approved"
    STATUS_REJECTED  = "rejected"
    STATUSES = [
        (STATUS_DRAFT,     "Draft"),
        (STATUS_SENT,      "Sent"),
        (STATUS_SUBMITTED, "Submitted"),
        (STATUS_APPROVED,  "Approved"),
        (STATUS_REJECTED,  "Rejected"),
    ]

    author = models.ForeignKey(
        Author, on_delete=models.PROTECT, related_name="legacy_invitations",
        help_text="The existing author this agreement is for.",
    )
    books = models.ManyToManyField(
        "Book", related_name="legacy_invitations", blank=True,
        help_text="Existing books this specific invitation/agreement covers.",
    )
    package = models.ForeignKey(
        DistributionPackage, on_delete=models.PROTECT, null=True, blank=True,
        related_name="legacy_invitations",
        help_text="Chosen by the author during signing — blank until submitted.",
    )

    token = models.UUIDField(default=uuid.uuid4, unique=True, editable=False, db_index=True)

    # Profile — same fields AuthorApplication captures, pre-filled from the
    # existing Author record client-side but stored here as what was
    # actually confirmed/typed at signing time.
    bio       = models.TextField(blank=True)
    address   = models.TextField(blank=True, help_text="Party address for the Distribution & Consignment Agreement.")
    id_number = models.CharField(
        max_length=100, blank=True,
        help_text="National ID / passport number, or company registration number for a legal entity.",
    )

    # Payment details fields come from PaymentDetailsMixin.

    # Signature / proof of agreement
    agreement_text_snapshot = models.TextField(blank=True)
    signed_name        = models.CharField(max_length=255, blank=True, help_text="Full name typed by the author as their signature.")
    signed_at          = models.DateTimeField(null=True, blank=True)
    signed_ip_address  = models.GenericIPAddressField(null=True, blank=True)

    # Lifecycle
    status     = models.CharField(max_length=20, choices=STATUSES, default=STATUS_DRAFT, db_index=True)
    created_by = models.ForeignKey(
        User, on_delete=models.SET_NULL, null=True, blank=True, related_name="+",
    )
    sent_at    = models.DateTimeField(null=True, blank=True)
    expires_at = models.DateTimeField(
        null=True, blank=True,
        help_text="Link is valid for 30 days from when it was (re)sent.",
    )

    # Review
    reviewed_by      = models.ForeignKey(
        User, on_delete=models.SET_NULL, null=True, blank=True, related_name="reviewed_legacy_invitations",
    )
    reviewed_at      = models.DateTimeField(null=True, blank=True)
    rejection_reason = models.TextField(blank=True)

    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]
        verbose_name = "Legacy Author Invitation"
        verbose_name_plural = "Legacy Author Invitations"

    def __str__(self):
        return f"{self.author.name} | {self.get_status_display()}"

    @property
    def is_expired(self) -> bool:
        return bool(self.expires_at) and timezone.now() > self.expires_at


class LegacyInvitationBookEdit(models.Model):
    """
    A change an author asked for, while signing a LegacyAuthorInvitation, to
    one of the existing books it covers — title, cover, and/or selling
    price. Sparse (only created for books actually edited) and staged: it
    does NOT touch the real Book until admin approval (approve_invitation()),
    same maker-checker principle as the rest of this flow. Blank fields mean
    "no change requested" for that field.
    """
    invitation = models.ForeignKey(LegacyAuthorInvitation, on_delete=models.CASCADE, related_name="book_edits")
    book       = models.ForeignKey("Book", on_delete=models.CASCADE, related_name="+")
    title      = models.CharField(max_length=512, blank=True, help_text="Leave blank to keep the current title.")
    cover      = models.ImageField(upload_to="legacy_invitation_covers/", blank=True, null=True)
    selling_price_kes = models.DecimalField(
        max_digits=10, decimal_places=2, null=True, blank=True,
        help_text="Leave blank to keep the current price.",
    )
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = (("invitation", "book"),)
        verbose_name = "Legacy Invitation Book Edit"
        verbose_name_plural = "Legacy Invitation Book Edits"

    def __str__(self):
        return f"Edit: {self.book.title} (invitation #{self.invitation_id})"


class Language(models.Model):
    name = models.CharField(max_length=100, unique=True)
    code = models.CharField(max_length=10, unique=True)

    def __str__(self):
        return self.name

class Format(models.Model):
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)

    def __str__(self):
        return self.name

class EBookPlatform(models.Model):
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)

    def __str__(self):
        return self.name

class Currency(models.Model):
    code = models.CharField(max_length=3, unique=True)
    name = models.CharField(max_length=100)

    class Meta:
        verbose_name_plural = "Currencies"

    def __str__(self):
        return self.code

class RightsType(models.Model):
    code = models.CharField(max_length=50, unique=True)
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.name

class Book(models.Model):
    catalog = models.ForeignKey(Catalog, on_delete=models.CASCADE, related_name='books')
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True, related_name='books', 
        verbose_name="Book Genre")
    author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True, blank=True, related_name='books')
    publisher = models.ForeignKey(
        Publisher, on_delete=models.SET_NULL, null=True, blank=True, related_name='books',
        help_text="If set, earnings/statements for this book go to the publisher instead of the author.",
    )
    title = models.CharField(max_length=512)
    slug = models.SlugField(
        max_length=300, unique=True, blank=True, null=True,
        help_text="URL-friendly identifier, auto-generated from the title if left blank.",
    )
    subtitle = models.CharField(max_length=512, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    cover = models.ImageField(upload_to='book_covers/', blank=True, null=True)
    publication_year = models.IntegerField(null=True, blank=True)
    isbn = models.CharField(max_length=50, blank=True, null=True)
    is_featured = models.BooleanField(default=False, help_text="Featured books will be displayed prominently.")
    is_listed = models.BooleanField(default=True, help_text="Uncheck this to hide the book from the public-facing website.")
    created_at = models.DateTimeField(auto_now_add=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    old_price = models.DecimalField(
        max_digits=10, decimal_places=2, null=True, blank=True,
        help_text="Set to show a strikethrough sale price (must be higher than price).",
    )
    rating = models.DecimalField(
        max_digits=2, decimal_places=1, null=True, blank=True,
        help_text="Average rating out of 5, e.g. 4.6.",
    )
    review_count = models.PositiveIntegerField(default=0, help_text="Number of reviews backing the rating.")
    stock = models.PositiveIntegerField(default=0, help_text="Physical copies available for purchase.")
    currency = models.ForeignKey(Currency, on_delete=models.SET_NULL, null=True, blank=True, related_name='books')
    available_languages = models.ManyToManyField(Language, blank=True, related_name='books')
    available_formats = models.ManyToManyField(Format, blank=True, related_name='books')
    selling_price_kes = models.DecimalField(
        max_digits=10, decimal_places=2, null=True, blank=True,
        help_text="KES retail price for physical book sales. Leave blank to use the main price.",
    )
    pos_price = models.DecimalField(
        max_digits=10, decimal_places=2, null=True, blank=True,
        help_text="Current price charged at Tai Bookstore/website (POS) — may be marked up above "
                   "selling_price_kes. The author's payout still stays fixed to the original "
                   "agreed price (selling_price_kes) regardless of this markup; the difference "
                   "goes to platform profit. Leave blank to just charge selling_price_kes.",
    )
    my_keep_percent = models.DecimalField(
        max_digits=5, decimal_places=2, null=True, blank=True,
        help_text="Tai AfroPress margin % for this book. Leave blank to use the author's default.",
    )
    reorder_level = models.PositiveIntegerField(
        default=5,
        help_text="Raise a low-stock alert when on-hand quantity reaches this level.",
    )
    track_inventory = models.BooleanField(
        default=True,
        help_text="Include this book in inventory tracking and reporting.",
    )
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = self._generate_unique_slug()
        super().save(*args, **kwargs)

    def _generate_unique_slug(self):
        base = slugify(self.title)[:290] or "book"
        slug = base
        suffix = 2
        while Book.objects.filter(slug=slug).exclude(pk=self.pk).exists():
            slug = f"{base}-{suffix}"
            suffix += 1
        return slug

    @property
    def effective_price(self):
        """
        The price to actually charge/display for this book, everywhere
        (POS, storefront browsing, cart, checkout): pos_price if a Tai
        Bookstore/website markup has been set, else selling_price_kes (the
        original agreed price), else the general price field.
        """
        return self.pos_price or self.selling_price_kes or self.price

    class Meta:
        ordering = ["title"]

class BookRight(models.Model):
    STATUS_CHOICES = [
        ('AVAILABLE', 'Available'),
        ('RESERVED', 'Reserved'),
        ('SOLD', 'Sold'),
        ('DISABLED', 'Disabled'),
    ]
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='book_rights')
    rights_type = models.ForeignKey(RightsType, on_delete=models.CASCADE, related_name='book_rights')
    price = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    currency = models.CharField(max_length=3, default='USD')
    exclusive = models.BooleanField(default=False)
    available_quantity = models.IntegerField(null=True, blank=True)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='AVAILABLE')
    additional_details = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = (('book', 'rights_type'),)

    def __str__(self):
        return f"{self.book.title} - {self.rights_type.code}"

class BookPlatformLink(models.Model):
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='platform_links')
    platform = models.ForeignKey(EBookPlatform, on_delete=models.CASCADE, related_name='book_links')
    url = models.URLField(max_length=1024)

    class Meta:
        unique_together = (('book', 'platform'),)

    def __str__(self):
        return f"{self.book.title} - {self.platform.name}"

class HomePageContent(models.Model):
    title = models.CharField(max_length=255)
    subtitle = models.TextField()
    background_image = models.ImageField(upload_to='homepage/', blank=True, null=True)
    button_text = models.CharField(max_length=50, default='Get Started')
    about_title_start = models.CharField(max_length=255, blank=True, null=True)
    about_title_end = models.CharField(max_length=255, blank=True, null=True)
    about_description = models.TextField(blank=True, null=True)
    services_title_start = models.CharField(max_length=255, blank=True, null=True)
    services_title_end = models.CharField(max_length=255, blank=True, null=True)
    services_description = models.TextField(blank=True, null=True)
    founder_headline_start = models.CharField(max_length=255, blank=True, null=True)
    founder_headline_end = models.CharField(max_length=255, blank=True, null=True)
    founder_title = models.CharField(max_length=255, blank=True, null=True)
    founder_image = models.ImageField(upload_to='homepage/founder/', blank=True, null=True)
    rights_agency_headline_start = models.CharField(max_length=255, blank=True, null=True)
    rights_agency_headline_end = models.CharField(max_length=255, blank=True, null=True)
    rights_agency_description = models.TextField(blank=True, null=True)
    rights_agency_button_text = models.CharField(max_length=50, blank=True, null=True)
    rights_agency_image = models.ImageField(upload_to='homepage/rights_agency/', blank=True, null=True)
    testimonials_title_start = models.CharField(max_length=255, blank=True, null=True)
    testimonials_title_end = models.CharField(max_length=255, blank=True, null=True)
    testimonials_description = models.TextField(blank=True, null=True)
    contact_title_start = models.CharField(max_length=255, blank=True, null=True)
    contact_title_end = models.CharField(max_length=255, blank=True, null=True)
    contact_description = models.TextField(blank=True, null=True)
    contact_email = models.EmailField(blank=True, null=True)
    contact_phone = models.CharField(max_length=50, blank=True, null=True)
    contact_address = models.CharField(max_length=255, blank=True, null=True)
    contact_facebook_url = models.URLField(blank=True, null=True)
    contact_instagram_url = models.URLField(blank=True, null=True)
    contact_linkedin_url = models.URLField(blank=True, null=True)
    contact_twitter_url = models.URLField(blank=True, null=True)
    newsletter_title = models.CharField(max_length=255, blank=True, null=True)
    newsletter_description = models.TextField(blank=True, null=True)
    footer_brand_name = models.CharField(max_length=100, blank=True, null=True)
    footer_description = models.TextField(blank=True, null=True)
    footer_quick_links_title = models.CharField(max_length=100, blank=True, null=True)
    footer_services_title = models.CharField(max_length=100, blank=True, null=True)
    footer_copyright_text = models.TextField(blank=True, null=True)
    is_active = models.BooleanField(default=False, help_text="Check this to make this content active on the home page. Any other active content will be deactivated.")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "Home Page Content"
        verbose_name_plural = "Home Page Content"

    def __str__(self):
        return f"Home Page Content ({'Active' if self.is_active else 'Inactive'}) - {self.title}"

    def save(self, *args, **kwargs):
        if self.is_active:
            HomePageContent.objects.filter(is_active=True).exclude(pk=self.pk).update(is_active=False)
        super().save(*args, **kwargs)

class NavigationItem(models.Model):
    homepage_content = models.ForeignKey(HomePageContent, on_delete=models.CASCADE, related_name='navigation_items')
    label = models.CharField(max_length=100)
    href = models.CharField(max_length=255, help_text="URL or anchor link (e.g., #home, /books).")
    order = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ['order']
        verbose_name = "Navigation Item"
        verbose_name_plural = "Navigation Items"

    def __str__(self):
        return self.label

class Service(models.Model):
    homepage_content = models.ForeignKey(HomePageContent, on_delete=models.CASCADE, related_name='services')
    title = models.CharField(max_length=100)
    description = models.TextField()
    icon = IconField(max_length=255, blank=True, null=True)
    order = models.PositiveIntegerField(default=0)
    button_active = models.BooleanField(default=False, help_text="Show the action button on this service card.")
    button_label = models.CharField(max_length=50, blank=True, help_text="e.g. \"Distribute With Us\"")
    button_url = models.CharField(max_length=255, blank=True, help_text="URL or path the button links to, e.g. /distribute.")

    class Meta:
        ordering = ['order']

    def __str__(self):
        return self.title

class FounderParagraph(models.Model):
    homepage_content = models.ForeignKey(HomePageContent, on_delete=models.CASCADE, related_name='founder_paragraphs')
    text = models.TextField()
    order = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ['order']

    def __str__(self):
        return f"Paragraph {self.order + 1}"

class FounderAchievement(models.Model):
    homepage_content = models.ForeignKey(HomePageContent, on_delete=models.CASCADE, related_name='founder_achievements')
    icon = IconField(max_length=255, blank=True, null=True)
    number = models.CharField(max_length=50)
    label = models.CharField(max_length=100)
    order = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ['order']

    def __str__(self):
        return self.label

class RightsAgencyFeature(models.Model):
    homepage_content = models.ForeignKey(HomePageContent, on_delete=models.CASCADE, related_name='rights_agency_features')
    text = models.CharField(max_length=255)
    order = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ['order']

    def __str__(self):
        return self.text

class Testimonial(models.Model):
    homepage_content = models.ForeignKey(HomePageContent, on_delete=models.CASCADE, related_name='testimonials')
    quote = models.TextField()
    author = models.CharField(max_length=255)
    title = models.CharField(max_length=255)
    order = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ['order']

    def __str__(self):
        return f"Testimonial by {self.author}"

class FooterQuickLink(models.Model):
    homepage_content = models.ForeignKey(HomePageContent, on_delete=models.CASCADE, related_name='footer_quick_links')
    text = models.CharField(max_length=100)
    url = models.CharField(max_length=255, help_text="Internal link (e.g., #about) or external URL.")
    order = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ['order']
        verbose_name = "Footer Quick Link"
        verbose_name_plural = "Footer Quick Links"

    def __str__(self):
        return self.text

class FooterServiceItem(models.Model):
    homepage_content = models.ForeignKey(HomePageContent, on_delete=models.CASCADE, related_name='footer_service_items')
    text = models.CharField(max_length=100)
    order = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ['order']
        verbose_name = "Footer Service Item"
        verbose_name_plural = "Footer Service Items"

    def __str__(self):
        return self.text

class ContactSubmission(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    email = models.EmailField()
    subject = models.CharField(max_length=255)
    message = models.TextField()
    submitted_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-submitted_at']
        verbose_name = "Contact Submission"
        verbose_name_plural = "Contact Submissions"

    def __str__(self):
        return f"Message from {self.first_name} {self.last_name} on {self.submitted_at.strftime('%Y-%m-%d')}"

class Subscriber(models.Model):
    email = models.EmailField(unique=True)
    token = models.UUIDField(default=uuid.uuid4, editable=False)
    is_active = models.BooleanField(default=True)
    subscribed_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.email

class NewsletterImage(models.Model):
    """
    Images uploaded (and cropped client-side) via the newsletter composer's
    block editor — not tied to a specific block/newsletter, since a block's
    config just stores the resulting URL. Kept as its own small gallery so
    uploads are visible/cleanable in the admin rather than invisible files.
    """
    image = models.ImageField(upload_to="newsletter_images/%Y/%m/")
    uploaded_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.image.name


class Newsletter(models.Model):
    BRAND_AFROPRESS = "afropress"
    BRAND_BOOKSTORE = "bookstore"
    BRAND_CHOICES = [
        (BRAND_AFROPRESS, "Tai AfroPress"),
        (BRAND_BOOKSTORE, "Tai BookStore"),
    ]

    STATUS_DRAFT   = "draft"
    STATUS_SENDING = "sending"
    STATUS_SENT    = "sent"
    STATUS_FAILED  = "failed"
    STATUS_CHOICES = [
        (STATUS_DRAFT, "Draft"),
        (STATUS_SENDING, "Sending"),
        (STATUS_SENT, "Sent"),
        (STATUS_FAILED, "Failed (partially sent)"),
    ]

    subject = models.CharField(max_length=255)
    preheader = models.CharField(
        max_length=255, blank=True,
        help_text="Short hidden preview text shown next to the subject in the inbox list.",
    )
    brand = models.CharField(max_length=10, choices=BRAND_CHOICES, default=BRAND_AFROPRESS)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default=STATUS_DRAFT, db_index=True)
    is_template = models.BooleanField(
        default=False,
        help_text="A reusable starting point (e.g. 'Featured Books') — never sent directly, excluded from the audience flow.",
    )

    # Legacy raw-HTML field from before the block composer — kept so old
    # newsletters still render, no longer written to by new ones.
    content = RichTextField(blank=True)

    # Reserved for future audience segmentation — NOT used by the send path,
    # which always queries Subscriber.objects.filter(is_active=True) fresh
    # so a newsletter's audience doesn't freeze at creation time.
    recipients = models.ManyToManyField(Subscriber, related_name='newsletters', blank=True)

    # Bulk-send progress/resume state (see catalog_app/services/newsletter_service.py)
    total_recipients = models.PositiveIntegerField(null=True, blank=True)
    sent_count = models.PositiveIntegerField(default=0)
    failed_count = models.PositiveIntegerField(default=0)
    send_cursor_subscriber_id = models.PositiveIntegerField(null=True, blank=True)
    send_started_at = models.DateTimeField(null=True, blank=True)

    created_at = models.DateTimeField(auto_now_add=True)
    sent_at = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return self.subject


class NewsletterBlock(models.Model):
    TYPE_HERO_IMAGE  = "hero_image"
    TYPE_HEADING     = "heading"
    TYPE_RICH_TEXT   = "rich_text"
    TYPE_IMAGE_TEXT  = "image_text"
    TYPE_BUTTON      = "button"
    TYPE_DIVIDER     = "divider"
    TYPE_SPACER      = "spacer"
    TYPE_BOOK        = "book_highlight"
    TYPE_FOOTER      = "footer_links"
    BLOCK_TYPE_CHOICES = [
        (TYPE_HERO_IMAGE, "Hero image"),
        (TYPE_HEADING, "Heading"),
        (TYPE_RICH_TEXT, "Rich text"),
        (TYPE_IMAGE_TEXT, "Image + text"),
        (TYPE_BUTTON, "Button / CTA"),
        (TYPE_DIVIDER, "Divider"),
        (TYPE_SPACER, "Spacer"),
        (TYPE_BOOK, "Book highlight"),
        (TYPE_FOOTER, "Footer links"),
    ]

    newsletter = models.ForeignKey(Newsletter, on_delete=models.CASCADE, related_name="blocks")
    block_type = models.CharField(max_length=30, choices=BLOCK_TYPE_CHOICES)
    position = models.PositiveIntegerField(default=0)
    config = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["position", "id"]

    def __str__(self):
        return f"{self.newsletter.subject} — {self.get_block_type_display()} #{self.position}"


class CartItem(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='cart_items')
    book_right = models.ForeignKey(BookRight, on_delete=models.CASCADE, related_name='cart_items')
    quantity = models.IntegerField(default=1)
    added_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = (('user', 'book_right'),)

    def __str__(self):
        return f"{self.user} - {self.book_right} x {self.quantity}"

class Order(models.Model):
    STATUS_CHOICES = [
        ('PENDING', 'Pending'),
        ('PAID', 'Paid'),
        ('FAILED', 'Failed'),
        ('CANCELLED', 'Cancelled'),
    ]
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders')
    total_amount = models.DecimalField(max_digits=12, decimal_places=2)
    currency = models.CharField(max_length=3, default='USD')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='PENDING')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"Order #{self.id} - {self.user} - {self.total_amount} {self.currency}"

class OrderItem(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_items')
    book_right = models.ForeignKey(BookRight, on_delete=models.PROTECT, related_name='order_items')
    unit_price = models.DecimalField(max_digits=12, decimal_places=2)
    quantity = models.IntegerField()
    total_price = models.DecimalField(max_digits=12, decimal_places=2)
    rights_snapshot = models.JSONField()
    created_at = models.DateTimeField(auto_now_add=True)

class Payment(models.Model):
    STATUS_CHOICES = [
        ('INITIATED','Initiated'),
        ('SUCCESS','Success'),
        ('FAILED','Failed'),
    ]
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='payments')
    provider = models.CharField(max_length=100, blank=True, null=True)
    provider_payment_id = models.CharField(max_length=255, blank=True, null=True)
    amount = models.DecimalField(max_digits=12, decimal_places=2)
    currency = models.CharField(max_length=3, default='USD')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='INITIATED')
    metadata = models.JSONField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
