# ============================================================
# ADDITIVE models for the SuperAdmin platform panel.
# Nothing existing is altered. Imported at the bottom of
# SuperAdmin/models.py so Django registers them.
# ============================================================

import uuid
from decimal import Decimal, ROUND_HALF_UP
import os

from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.db import models
from django.db.models import Sum
from django.utils import timezone

from Company.models import company_details


def get_private_storage():
    """Documents live in private_media/ (never served by MEDIA_URL)."""
    return FileSystemStorage(
        location=os.path.join(settings.BASE_DIR, "private_media")
    )


class PlatformAuditFields(models.Model):
    created_by = models.CharField(max_length=150, null=True, blank=True)
    updated_by = models.CharField(max_length=150, null=True, blank=True)
    id_version = models.PositiveIntegerField(default=1)
    is_active = models.BooleanField(default=True)

    class Meta:
        abstract = True


# ------------------------------------------------------------
# ROLES
# ------------------------------------------------------------

class StaffRole(PlatformAuditFields):
    name = models.CharField(max_length=100, unique=True)
    code = models.SlugField(max_length=40, unique=True)
    description = models.CharField(max_length=255, blank=True, default="")
    permissions = models.JSONField(default=list, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["name"]

    def __str__(self):
        return self.name


class StaffRoleAssignment(PlatformAuditFields):
    profile = models.OneToOneField(
        "SuperAdmin.SuperAdminProfile",
        on_delete=models.CASCADE,
        related_name="staff_role",
    )
    role = models.ForeignKey(
        StaffRole, on_delete=models.PROTECT, related_name="assignments"
    )
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.profile} -> {self.role}"


# ------------------------------------------------------------
# REGISTRATION WORKFLOW
# ------------------------------------------------------------

class RegistrationRequest(PlatformAuditFields):
    STATUS_PENDING = "PENDING"
    STATUS_APPROVED = "APPROVED"
    STATUS_REJECTED = "REJECTED"
    STATUS_CHOICES = [
        (STATUS_PENDING, "Pending"),
        (STATUS_APPROVED, "Approved"),
        (STATUS_REJECTED, "Rejected"),
    ]

    reference = models.CharField(max_length=24, unique=True, blank=True)
    company_name = models.CharField(max_length=100)
    brand_name = models.CharField(max_length=100, blank=True, default="")
    contact_person = models.CharField(max_length=150)
    email = models.EmailField()
    phone = models.CharField(max_length=15)
    website = models.CharField(max_length=50, blank=True, default="")
    industry_type = models.CharField(max_length=100, blank=True, default="")
    address = models.CharField(max_length=500, blank=True, default="")
    employee_count = models.PositiveIntegerField(default=0)
    requested_package = models.ForeignKey(
        "SuperAdmin.SubscriptionPackage",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="registration_requests",
    )
    message = models.CharField(max_length=1000, blank=True, default="")
    document = models.FileField(
        storage=get_private_storage,
        upload_to="registration_docs/%Y/%m/",
        null=True,
        blank=True,
    )
    status = models.CharField(
        max_length=10, choices=STATUS_CHOICES, default=STATUS_PENDING, db_index=True
    )
    reviewed_by_name = models.CharField(max_length=150, blank=True, default="")
    reviewed_at = models.DateTimeField(null=True, blank=True)
    rejection_reason = models.TextField(blank=True, default="")
    company = models.ForeignKey(
        company_details,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="registration_requests",
    )
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-created_at"]

    def save(self, *args, **kwargs):
        if not self.reference:
            while True:
                ref = "REG-%s-%s" % (
                    timezone.now().strftime("%Y%m%d"),
                    uuid.uuid4().hex[:6].upper(),
                )
                if not RegistrationRequest.objects.filter(reference=ref).exists():
                    self.reference = ref
                    break
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.reference} - {self.company_name}"


class RegistrationEvent(PlatformAuditFields):
    request = models.ForeignKey(
        RegistrationRequest, on_delete=models.CASCADE, related_name="events"
    )
    action = models.CharField(max_length=30)
    note = models.TextField(blank=True, default="")
    actor = models.CharField(max_length=150, blank=True, default="")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["created_at"]


# ------------------------------------------------------------
# PLATFORM BILLING (what companies owe the platform;
# distinct from Company.Invoice which is a company's own
# client invoicing)
# ------------------------------------------------------------

class PlatformInvoice(PlatformAuditFields):
    STATUS_DRAFT = "DRAFT"
    STATUS_ISSUED = "ISSUED"
    STATUS_PARTIAL = "PARTIAL"
    STATUS_PAID = "PAID"
    STATUS_CANCELLED = "CANCELLED"
    STATUS_CHOICES = [
        (STATUS_DRAFT, "Draft"),
        (STATUS_ISSUED, "Issued"),
        (STATUS_PARTIAL, "Partially paid"),
        (STATUS_PAID, "Paid"),
        (STATUS_CANCELLED, "Cancelled"),
    ]
    CYCLE_CHOICES = [
        ("MONTHLY", "Monthly"),
        ("YEARLY", "Yearly"),
        ("CUSTOM", "Custom"),
    ]

    company = models.ForeignKey(
        company_details, on_delete=models.CASCADE, related_name="platform_invoices"
    )
    package = models.ForeignKey(
        "SuperAdmin.SubscriptionPackage",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="platform_invoices",
    )
    invoice_number = models.CharField(max_length=30, unique=True, blank=True)
    billing_cycle = models.CharField(
        max_length=10, choices=CYCLE_CHOICES, default="MONTHLY"
    )
    period_start = models.DateField(null=True, blank=True)
    period_end = models.DateField(null=True, blank=True)
    amount = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    tax_percent = models.DecimalField(max_digits=5, decimal_places=2, default=18)
    tax_amount = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    total_amount = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    issue_date = models.DateField(default=timezone.localdate)
    due_date = models.DateField()
    status = models.CharField(
        max_length=10, choices=STATUS_CHOICES, default=STATUS_ISSUED, db_index=True
    )
    notes = models.CharField(max_length=500, blank=True, default="")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-created_at"]

    def save(self, *args, **kwargs):
        amount = Decimal(self.amount or 0)
        pct = Decimal(self.tax_percent or 0)
        self.tax_amount = (amount * pct / Decimal(100)).quantize(
            Decimal("0.01"), rounding=ROUND_HALF_UP
        )
        self.total_amount = amount + self.tax_amount
        if not self.invoice_number:
            prefix = "INV-%s-" % timezone.now().strftime("%Y%m")
            n = PlatformInvoice.objects.filter(
                invoice_number__startswith=prefix
            ).count() + 1
            while PlatformInvoice.objects.filter(
                invoice_number=f"{prefix}{n:04d}"
            ).exists():
                n += 1
            self.invoice_number = f"{prefix}{n:04d}"
        super().save(*args, **kwargs)

    def amount_paid(self):
        return self.payments.filter(is_active=True).aggregate(
            s=Sum("amount")
        )["s"] or Decimal("0")

    def balance(self):
        return Decimal(self.total_amount) - self.amount_paid()

    @property
    def is_overdue(self):
        return (
            self.status in (self.STATUS_ISSUED, self.STATUS_PARTIAL)
            and self.due_date < timezone.localdate()
        )

    def refresh_status(self):
        if self.status in (self.STATUS_DRAFT, self.STATUS_CANCELLED):
            return
        paid = self.amount_paid()
        if paid >= Decimal(self.total_amount) and Decimal(self.total_amount) > 0:
            new = self.STATUS_PAID
        elif paid > 0:
            new = self.STATUS_PARTIAL
        else:
            new = self.STATUS_ISSUED
        if new != self.status:
            self.status = new
            self.save(update_fields=["status", "updated_at"])

    def __str__(self):
        return self.invoice_number


class PlatformPayment(PlatformAuditFields):
    METHOD_CHOICES = [
        ("UPI", "UPI"),
        ("BANK", "Bank transfer"),
        ("CARD", "Card"),
        ("CASH", "Cash"),
        ("CHEQUE", "Cheque"),
        ("OTHER", "Other"),
    ]
    invoice = models.ForeignKey(
        PlatformInvoice, on_delete=models.CASCADE, related_name="payments"
    )
    amount = models.DecimalField(max_digits=12, decimal_places=2)
    method = models.CharField(max_length=10, choices=METHOD_CHOICES, default="BANK")
    reference = models.CharField(max_length=100, blank=True, default="")
    paid_on = models.DateField(default=timezone.localdate)
    recorded_by = models.CharField(max_length=150, blank=True, default="")
    notes = models.CharField(max_length=300, blank=True, default="")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-paid_on", "-id"]

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        self.invoice.refresh_status()

    def __str__(self):
        return f"{self.invoice.invoice_number} - {self.amount}"
