"""
catalog_app/services/author_application_service.py
─────────────────────────────────────────────────────
Reviewing an AuthorApplication: approving creates the real Author + Book
records (mirrors the PendingInventoryTransaction maker-checker pattern —
nothing becomes "real" until an admin approves it). Rejecting just closes
the application out with a reason.
"""

from django.db import transaction
from django.utils import timezone

from catalog_app.models import Author, AuthorApplication, Book, PaymentDetailsMixin

# Copying by field name (rather than a hardcoded kwarg list) means this stays
# correct automatically if PaymentDetailsMixin's fields ever change.
_PAYMENT_FIELD_NAMES = [f.name for f in PaymentDetailsMixin._meta.get_fields()]


@transaction.atomic
def approve_application(*, application: AuthorApplication, user=None) -> Author:
    if application.status != AuthorApplication.STATUS_PENDING:
        raise ValueError(f"Application is not pending (current: {application.get_status_display()}).")

    books = list(application.books.all())
    if not books:
        raise ValueError("Application has no books to create.")

    missing_catalog = [b.title for b in books if b.catalog_id is None]
    if missing_catalog:
        raise ValueError(
            "Assign a catalog (collection) to every book before approving — missing for: "
            + ", ".join(missing_catalog)
        )

    payment_kwargs = {name: getattr(application, name) for name in _PAYMENT_FIELD_NAMES}
    author = Author.objects.create(
        name=application.full_name,
        email=application.email,
        bio=application.bio,
        address=application.address,
        id_number=application.id_number,
        default_my_keep_percent=application.package.my_keep_percent,
        **payment_kwargs,
    )

    for app_book in books:
        book = Book.objects.create(
            author=author,
            catalog=app_book.catalog,
            title=app_book.title,
            isbn=app_book.isbn,
            category=app_book.category,
            description=app_book.description,
            cover=app_book.cover,
            publication_year=app_book.publication_year,
            selling_price_kes=app_book.selling_price_kes,
            price=app_book.selling_price_kes,
            # Snapshot the chosen package's margin onto the book itself
            # rather than relying solely on Author.default_my_keep_percent —
            # so a later change to the author's default (e.g. from a
            # different application) can't silently alter what this book's
            # terms actually were at approval time.
            my_keep_percent=application.package.my_keep_percent,
            is_listed=False,  # stays hidden until stock is actually received — see receive_stock()
        )
        app_book.created_book = book
        app_book.save(update_fields=["created_book"])

    application.status = AuthorApplication.STATUS_APPROVED
    application.reviewed_by = user
    application.reviewed_at = timezone.now()
    application.created_author = author
    application.save(update_fields=["status", "reviewed_by", "reviewed_at", "created_author"])

    return author


def reject_application(*, application: AuthorApplication, reason: str, user=None) -> AuthorApplication:
    if application.status != AuthorApplication.STATUS_PENDING:
        raise ValueError(f"Application is not pending (current: {application.get_status_display()}).")

    application.status = AuthorApplication.STATUS_REJECTED
    application.rejection_reason = reason
    application.reviewed_by = user
    application.reviewed_at = timezone.now()
    application.save(update_fields=["status", "rejection_reason", "reviewed_by", "reviewed_at"])
    return application
