"""
SCM ORM Models — Infrastructure Layer.

مدل‌های Django ORM ماژول خرید و تدارکات.
تمام جداول با پیشوند scm_ هستند.
verbose_name‌ها به فارسی.
"""
import uuid

from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _

from apps.core.tenant.models import TenantAwareModel


# ═══════════════════════════════════════════════════
# 1️⃣  VENDOR MANAGEMENT
# ═══════════════════════════════════════════════════

class VendorCategoryModel(TenantAwareModel):
    """دسته‌بندی تأمین‌کنندگان — سلسله‌مراتبی."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    category_code = models.CharField(_("کد"), max_length=50, db_index=True)
    category_name = models.CharField(_("نام دسته‌بندی"), max_length=255)
    parent_category = models.ForeignKey(
        "self", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="children", verbose_name=_("دسته‌بندی مادر"),
    )
    level = models.PositiveIntegerField(_("سطح"), default=0)
    description = models.TextField(_("توضیحات"), blank=True)
    is_active = models.BooleanField(_("فعال"), default=True, db_index=True)

    created_at = models.DateTimeField(_("تاریخ ایجاد"), auto_now_add=True)
    updated_at = models.DateTimeField(_("تاریخ بروزرسانی"), auto_now=True)
    created_by = models.UUIDField(_("ایجاد توسط"), null=True, blank=True)
    updated_by = models.UUIDField(_("بروزرسانی توسط"), null=True, blank=True)

    class Meta:
        app_label = "scm"
        db_table = "scm_vendor_category"
        verbose_name = _("دسته‌بندی تأمین‌کننده")
        verbose_name_plural = _("دسته‌بندی تأمین‌کنندگان")
        unique_together = [["tenant", "category_code"]]
        indexes = [models.Index(fields=["tenant", "is_active"])]

    def __str__(self):
        return self.category_name


class VendorModel(TenantAwareModel):
    """تأمین‌کننده — جدول اصلی."""

    class VendorStatus(models.TextChoices):
        ACTIVE = "ACTIVE", _("فعال")
        INACTIVE = "INACTIVE", _("غیرفعال")
        BLOCKED = "BLOCKED", _("مسدود")
        PENDING_APPROVAL = "PENDING_APPROVAL", _("در انتظار تأیید")

    class VendorType(models.TextChoices):
        INDIVIDUAL = "INDIVIDUAL", _("حقیقی")
        COMPANY = "COMPANY", _("حقوقی")
        GOVERNMENT = "GOVERNMENT", _("دولتی")

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    vendor_code = models.CharField(_("کد تأمین‌کننده"), max_length=50, db_index=True)
    vendor_name = models.CharField(_("نام تأمین‌کننده"), max_length=255)
    vendor_name_en = models.CharField(_("نام انگلیسی"), max_length=255, blank=True)
    vendor_type = models.CharField(
        _("نوع"), max_length=20,
        choices=VendorType.choices, default=VendorType.COMPANY,
    )
    category = models.ForeignKey(
        VendorCategoryModel, on_delete=models.SET_NULL, null=True, blank=True,
        related_name="vendors", verbose_name=_("دسته‌بندی"),
    )
    status = models.CharField(
        _("وضعیت"), max_length=20,
        choices=VendorStatus.choices, default=VendorStatus.PENDING_APPROVAL,
        db_index=True,
    )

    # Identification
    national_id = models.CharField(_("شناسه ملی / کد ملی"), max_length=20, blank=True)
    economic_code = models.CharField(_("کد اقتصادی"), max_length=20, blank=True)
    registration_number = models.CharField(_("شماره ثبت"), max_length=50, blank=True)

    # Communication
    phone = models.CharField(_("تلفن"), max_length=20, blank=True)
    fax = models.CharField(_("فکس"), max_length=20, blank=True)
    email = models.EmailField(_("ایمیل"), blank=True)
    website = models.URLField(_("وب‌سایت"), blank=True)

    # HRM Link
    representative_employee_id = models.UUIDField(
        _("نماینده داخلی (کارمند)"), null=True, blank=True,
    )

    # Settings
    payment_terms_days = models.PositiveIntegerField(_("مهلت پرداخت (روز)"), default=30)
    credit_limit = models.BigIntegerField(_("سقف اعتبار"), default=0)
    currency_code = models.CharField(_("ارز"), max_length=10, default="IRR")

    # Metadata
    notes = models.TextField(_("یادداشت"), blank=True)
    is_active = models.BooleanField(_("فعال"), default=True, db_index=True)

    created_at = models.DateTimeField(_("تاریخ ایجاد"), auto_now_add=True)
    updated_at = models.DateTimeField(_("تاریخ بروزرسانی"), auto_now=True)
    created_by = models.UUIDField(_("ایجاد توسط"), null=True, blank=True)
    updated_by = models.UUIDField(_("بروزرسانی توسط"), null=True, blank=True)

    class Meta:
        app_label = "scm"
        db_table = "scm_vendor"
        verbose_name = _("تأمین‌کننده")
        verbose_name_plural = _("تأمین‌کنندگان")
        unique_together = [["tenant", "vendor_code"]]
        indexes = [
            models.Index(fields=["tenant", "status"]),
            models.Index(fields=["tenant", "is_active"]),
            models.Index(fields=["tenant", "category"]),
        ]

    def __str__(self):
        return f"{self.vendor_code} — {self.vendor_name}"


class VendorContactModel(TenantAwareModel):
    """مخاطب تأمین‌کننده."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    vendor = models.ForeignKey(
        VendorModel, on_delete=models.CASCADE,
        related_name="contacts", verbose_name=_("تأمین‌کننده"),
    )
    contact_name = models.CharField(_("نام مخاطب"), max_length=255)
    contact_title = models.CharField(_("سمت"), max_length=100, blank=True)
    phone = models.CharField(_("تلفن"), max_length=20, blank=True)
    mobile = models.CharField(_("موبایل"), max_length=20, blank=True)
    email = models.EmailField(_("ایمیل"), blank=True)
    is_primary = models.BooleanField(_("مخاطب اصلی"), default=False)
    is_active = models.BooleanField(_("فعال"), default=True)

    created_at = models.DateTimeField(_("تاریخ ایجاد"), auto_now_add=True)
    updated_at = models.DateTimeField(_("تاریخ بروزرسانی"), auto_now=True)

    class Meta:
        app_label = "scm"
        db_table = "scm_vendor_contact"
        verbose_name = _("مخاطب تأمین‌کننده")
        verbose_name_plural = _("مخاطبین تأمین‌کنندگان")

    def __str__(self):
        return f"{self.contact_name} ({self.vendor.vendor_name})"


class VendorBankAccountModel(TenantAwareModel):
    """حساب بانکی تأمین‌کننده."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    vendor = models.ForeignKey(
        VendorModel, on_delete=models.CASCADE,
        related_name="bank_accounts", verbose_name=_("تأمین‌کننده"),
    )
    bank_name = models.CharField(_("نام بانک"), max_length=100)
    branch_name = models.CharField(_("نام شعبه"), max_length=100, blank=True)
    account_number = models.CharField(_("شماره حساب"), max_length=50)
    iban = models.CharField(_("شبا"), max_length=34, blank=True)
    account_holder_name = models.CharField(_("نام صاحب حساب"), max_length=255, blank=True)
    is_default = models.BooleanField(_("پیش‌فرض"), default=False)
    is_active = models.BooleanField(_("فعال"), default=True)

    created_at = models.DateTimeField(_("تاریخ ایجاد"), auto_now_add=True)
    updated_at = models.DateTimeField(_("تاریخ بروزرسانی"), auto_now=True)

    class Meta:
        app_label = "scm"
        db_table = "scm_vendor_bank_account"
        verbose_name = _("حساب بانکی تأمین‌کننده")
        verbose_name_plural = _("حساب‌های بانکی تأمین‌کنندگان")

    def __str__(self):
        return f"{self.bank_name} — {self.account_number}"


class VendorAddressModel(TenantAwareModel):
    """آدرس تأمین‌کننده."""

    class AddressType(models.TextChoices):
        MAIN = "MAIN", _("اصلی")
        BILLING = "BILLING", _("صورتحساب")
        SHIPPING = "SHIPPING", _("ارسال")
        WAREHOUSE = "WAREHOUSE", _("انبار")

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    vendor = models.ForeignKey(
        VendorModel, on_delete=models.CASCADE,
        related_name="addresses", verbose_name=_("تأمین‌کننده"),
    )
    address_type = models.CharField(
        _("نوع آدرس"), max_length=20,
        choices=AddressType.choices, default=AddressType.MAIN,
    )
    address_line1 = models.CharField(_("آدرس خط ۱"), max_length=500)
    address_line2 = models.CharField(_("آدرس خط ۲"), max_length=500, blank=True)
    city = models.CharField(_("شهر"), max_length=100, blank=True)
    province = models.CharField(_("استان"), max_length=100, blank=True)
    postal_code = models.CharField(_("کد پستی"), max_length=20, blank=True)
    country = models.CharField(_("کشور"), max_length=5, default="IR")
    phone = models.CharField(_("تلفن"), max_length=20, blank=True)
    fax = models.CharField(_("فکس"), max_length=20, blank=True)
    is_default = models.BooleanField(_("پیش‌فرض"), default=False)

    created_at = models.DateTimeField(_("تاریخ ایجاد"), auto_now_add=True)
    updated_at = models.DateTimeField(_("تاریخ بروزرسانی"), auto_now=True)

    class Meta:
        app_label = "scm"
        db_table = "scm_vendor_address"
        verbose_name = _("آدرس تأمین‌کننده")
        verbose_name_plural = _("آدرس‌های تأمین‌کنندگان")

    def __str__(self):
        return f"{self.get_address_type_display()} — {self.city}"
