from __future__ import annotations

from typing import ClassVar

from django.db import models
from django.utils.translation import gettext_lazy as _

from simorgh.core.models import TimeStampedModel, UUIDModel


class TenantStatus(models.TextChoices):
    ACTIVE = "active", _("Active")
    SUSPENDED = "suspended", _("Suspended")
    ARCHIVED = "archived", _("Archived")


class Tenant(UUIDModel, TimeStampedModel):
    """An isolated workspace. All scoped data lives under exactly one tenant."""

    slug = models.SlugField(_("slug"), max_length=64, unique=True)
    name = models.CharField(_("name"), max_length=255)
    status = models.CharField(
        _("status"),
        max_length=16,
        choices=TenantStatus.choices,
        default=TenantStatus.ACTIVE,
        db_index=True,
    )
    # Deprecated: plan_ref is kept for backward-compatibility during migration.
    # Use plan FK below as the authoritative plan reference.
    plan_ref = models.CharField(_("plan reference"), max_length=64, blank=True, default="")
    plan = models.ForeignKey(
        "subscription.PlatformPlan",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="tenants",
        verbose_name=_("subscription plan"),
        help_text=_("Select the platform plan for this tenant."),
    )
    settings = models.JSONField(_("settings"), default=dict, blank=True)

    class Meta:
        verbose_name = _("tenant")
        verbose_name_plural = _("tenants")
        ordering: ClassVar[list[str]] = ["slug"]

    def __str__(self) -> str:
        return self.slug

    @property
    def is_active(self) -> bool:
        return self.status == TenantStatus.ACTIVE

    @property
    def current_plan_code(self) -> str:
        """Return the current plan code from the FK, falling back to TenantSubscription or plan_ref."""
        if self.plan_id is not None:
            try:
                return self.plan.code
            except Exception:  # noqa: BLE001
                pass
        try:
            from simorgh.apps.subscription.models import TenantSubscription
            sub = TenantSubscription.objects.filter(tenant_id=self.pk).select_related("plan").first()
            if sub is not None:
                return sub.plan.code
        except Exception:  # noqa: BLE001
            pass
        return self.plan_ref
