"""
SCM ORM Models Extended — PR, RFQ, PO, GR, Return, Evaluation, Price.
"""
import uuid

from django.db import models
from django.utils.translation import gettext_lazy as _

from apps.core.tenant.models import TenantAwareModel
from .models import VendorModel, VendorCategoryModel


# ═══════════════════════════════════════════════════
# 2️⃣  PURCHASE REQUISITION
# ═══════════════════════════════════════════════════

class PurchaseRequisitionModel(TenantAwareModel):
    """درخواست خرید."""

    class PRStatus(models.TextChoices):
        DRAFT = "DRAFT", _("پیش‌نویس")
        PENDING_APPROVAL = "PENDING_APPROVAL", _("در انتظار تأیید")
        APPROVED = "APPROVED", _("تأیید شده")
        REJECTED = "REJECTED", _("رد شده")
        CONVERTED = "CONVERTED", _("تبدیل شده")
        PARTIALLY_CONVERTED = "PARTIALLY_CONVERTED", _("تبدیل جزئی")
        CANCELLED = "CANCELLED", _("لغو شده")

    class PRPriority(models.TextChoices):
        LOW = "LOW", _("کم")
        NORMAL = "NORMAL", _("عادی")
        HIGH = "HIGH", _("زیاد")
        URGENT = "URGENT", _("فوری")

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    pr_number = models.CharField(_("شماره درخواست"), max_length=50, db_index=True)
    title = models.CharField(_("عنوان"), max_length=255, blank=True)
    description = models.TextField(_("توضیحات"), blank=True)
    status = models.CharField(
        _("وضعیت"), max_length=25,
        choices=PRStatus.choices, default=PRStatus.DRAFT, db_index=True,
    )
    priority = models.CharField(
        _("اولویت"), max_length=10,
        choices=PRPriority.choices, default=PRPriority.NORMAL,
    )

    requester_id = models.UUIDField(_("درخواست‌دهنده"), null=True, blank=True)
    requester_name = models.CharField(_("نام درخواست‌دهنده"), max_length=255, blank=True)
    department = models.CharField(_("واحد سازمانی"), max_length=255, blank=True)

    request_date = models.DateField(_("تاریخ درخواست"), null=True, blank=True)
    required_date = models.DateField(_("تاریخ نیاز"), null=True, blank=True)

    total_estimated_amount = models.DecimalField(
        _("مبلغ تخمینی کل"), max_digits=20, decimal_places=2, default=0,
    )
    currency_code = models.CharField(_("ارز"), max_length=10, default="IRR")

    approved_by_id = models.UUIDField(_("تأیید توسط"), null=True, blank=True)
    approved_at = models.DateTimeField(_("تاریخ تأیید"), null=True, blank=True)
    rejection_reason = models.TextField(_("دلیل رد"), blank=True)

    notes = models.TextField(_("یادداشت"), blank=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_purchase_requisition"
        verbose_name = _("درخواست خرید")
        verbose_name_plural = _("درخواست‌های خرید")
        unique_together = [["tenant", "pr_number"]]
        indexes = [
            models.Index(fields=["tenant", "status"]),
            models.Index(fields=["tenant", "requester_id"]),
        ]

    def __str__(self):
        return self.pr_number


class PurchaseRequisitionLineModel(TenantAwareModel):
    """آیتم درخواست خرید."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    requisition = models.ForeignKey(
        PurchaseRequisitionModel, on_delete=models.CASCADE,
        related_name="lines", verbose_name=_("درخواست خرید"),
    )
    line_number = models.PositiveIntegerField(_("ردیف"), default=0)
    item_id = models.UUIDField(_("کالا"), null=True, blank=True)
    item_code = models.CharField(_("کد کالا"), max_length=50, blank=True)
    item_name = models.CharField(_("نام کالا"), max_length=255, blank=True)
    description = models.TextField(_("توضیحات"), blank=True)
    quantity = models.DecimalField(_("مقدار"), max_digits=18, decimal_places=4, default=0)
    uom_id = models.UUIDField(_("واحد"), null=True, blank=True)
    uom_code = models.CharField(_("کد واحد"), max_length=20, blank=True)
    estimated_unit_price = models.DecimalField(
        _("قیمت واحد تخمینی"), max_digits=20, decimal_places=2, default=0,
    )
    estimated_total_price = models.DecimalField(
        _("مبلغ تخمینی"), max_digits=20, decimal_places=2, default=0,
    )
    required_date = models.DateField(_("تاریخ نیاز"), null=True, blank=True)
    warehouse_id = models.UUIDField(_("انبار مقصد"), null=True, blank=True)
    warehouse_name = models.CharField(_("نام انبار"), max_length=255, blank=True)
    preferred_vendor_id = models.UUIDField(_("تأمین‌کننده ترجیحی"), null=True, blank=True)
    notes = models.TextField(_("یادداشت"), blank=True)
    is_converted = models.BooleanField(_("تبدیل شده"), default=False)
    converted_po_id = models.UUIDField(_("سفارش خرید"), null=True, blank=True)

    created_at = models.DateTimeField(_("تاریخ ایجاد"), auto_now_add=True)
    updated_at = models.DateTimeField(_("تاریخ بروزرسانی"), auto_now=True)

    class Meta:
        app_label = "scm"
        db_table = "scm_purchase_requisition_line"
        verbose_name = _("آیتم درخواست خرید")
        verbose_name_plural = _("آیتم‌های درخواست خرید")
        ordering = ["line_number"]


# ═══════════════════════════════════════════════════
# 3️⃣  RFQ
# ═══════════════════════════════════════════════════

class RFQModel(TenantAwareModel):
    """درخواست استعلام."""

    class RFQStatus(models.TextChoices):
        DRAFT = "DRAFT", _("پیش‌نویس")
        SENT = "SENT", _("ارسال شده")
        CLOSED = "CLOSED", _("بسته شده")
        CANCELLED = "CANCELLED", _("لغو شده")
        AWARDED = "AWARDED", _("واگذار شده")

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    rfq_number = models.CharField(_("شماره استعلام"), max_length=50, db_index=True)
    title = models.CharField(_("عنوان"), max_length=255, blank=True)
    description = models.TextField(_("توضیحات"), blank=True)
    status = models.CharField(
        _("وضعیت"), max_length=20,
        choices=RFQStatus.choices, default=RFQStatus.DRAFT, db_index=True,
    )

    pr_id = models.UUIDField(_("درخواست خرید"), null=True, blank=True)
    pr_number = models.CharField(_("شماره درخواست خرید"), max_length=50, blank=True)

    issue_date = models.DateField(_("تاریخ صدور"), null=True, blank=True)
    closing_date = models.DateField(_("تاریخ پایان"), null=True, blank=True)
    required_date = models.DateField(_("تاریخ نیاز"), null=True, blank=True)

    buyer_id = models.UUIDField(_("خریدار"), null=True, blank=True)
    buyer_name = models.CharField(_("نام خریدار"), max_length=255, blank=True)

    currency_code = models.CharField(_("ارز"), max_length=10, default="IRR")
    notes = models.TextField(_("یادداشت"), blank=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_rfq"
        verbose_name = _("درخواست استعلام")
        verbose_name_plural = _("درخواست‌های استعلام")
        unique_together = [["tenant", "rfq_number"]]
        indexes = [models.Index(fields=["tenant", "status"])]

    def __str__(self):
        return self.rfq_number


class RFQLineModel(TenantAwareModel):
    """آیتم استعلام."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    rfq = models.ForeignKey(
        RFQModel, on_delete=models.CASCADE,
        related_name="lines", verbose_name=_("استعلام"),
    )
    line_number = models.PositiveIntegerField(_("ردیف"), default=0)
    item_id = models.UUIDField(_("کالا"), null=True, blank=True)
    item_code = models.CharField(_("کد کالا"), max_length=50, blank=True)
    item_name = models.CharField(_("نام کالا"), max_length=255, blank=True)
    description = models.TextField(_("توضیحات"), blank=True)
    quantity = models.DecimalField(_("مقدار"), max_digits=18, decimal_places=4, default=0)
    uom_id = models.UUIDField(_("واحد"), null=True, blank=True)
    uom_code = models.CharField(_("کد واحد"), max_length=20, blank=True)
    required_date = models.DateField(_("تاریخ نیاز"), null=True, blank=True)
    notes = models.TextField(_("یادداشت"), blank=True)

    created_at = models.DateTimeField(_("تاریخ ایجاد"), auto_now_add=True)

    class Meta:
        app_label = "scm"
        db_table = "scm_rfq_line"
        verbose_name = _("آیتم استعلام")
        verbose_name_plural = _("آیتم‌های استعلام")
        ordering = ["line_number"]


class RFQInvitedVendorModel(TenantAwareModel):
    """تأمین‌کنندگان دعوت‌شده به استعلام."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    rfq = models.ForeignKey(
        RFQModel, on_delete=models.CASCADE,
        related_name="invited_vendors", verbose_name=_("استعلام"),
    )
    vendor = models.ForeignKey(
        VendorModel, on_delete=models.CASCADE,
        related_name="rfq_invitations", verbose_name=_("تأمین‌کننده"),
    )
    invited_at = models.DateTimeField(_("تاریخ دعوت"), auto_now_add=True)

    class Meta:
        app_label = "scm"
        db_table = "scm_rfq_invited_vendor"
        verbose_name = _("تأمین‌کننده دعوت‌شده")
        verbose_name_plural = _("تأمین‌کنندگان دعوت‌شده")
        unique_together = [["rfq", "vendor"]]


class RFQVendorResponseModel(TenantAwareModel):
    """پاسخ تأمین‌کننده."""

    class ResponseStatus(models.TextChoices):
        PENDING = "PENDING", _("در انتظار")
        RECEIVED = "RECEIVED", _("دریافت شده")
        AWARDED = "AWARDED", _("برنده")
        REJECTED = "REJECTED", _("رد شده")

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    rfq = models.ForeignKey(
        RFQModel, on_delete=models.CASCADE,
        related_name="vendor_responses", verbose_name=_("استعلام"),
    )
    vendor = models.ForeignKey(
        VendorModel, on_delete=models.CASCADE,
        related_name="rfq_responses", verbose_name=_("تأمین‌کننده"),
    )
    status = models.CharField(
        _("وضعیت"), max_length=20,
        choices=ResponseStatus.choices, default=ResponseStatus.PENDING,
    )
    response_date = models.DateField(_("تاریخ پاسخ"), null=True, blank=True)
    validity_date = models.DateField(_("اعتبار تا"), null=True, blank=True)
    total_amount = models.DecimalField(
        _("مبلغ کل"), max_digits=20, decimal_places=2, default=0,
    )
    currency_code = models.CharField(_("ارز"), max_length=10, default="IRR")
    payment_terms = models.CharField(_("شرایط پرداخت"), max_length=500, blank=True)
    delivery_terms = models.CharField(_("شرایط تحویل"), max_length=500, blank=True)
    notes = models.TextField(_("یادداشت"), blank=True)

    created_at = models.DateTimeField(_("تاریخ ایجاد"), auto_now_add=True)
    updated_at = models.DateTimeField(_("تاریخ بروزرسانی"), auto_now=True)

    class Meta:
        app_label = "scm"
        db_table = "scm_rfq_vendor_response"
        verbose_name = _("پاسخ تأمین‌کننده")
        verbose_name_plural = _("پاسخ‌های تأمین‌کنندگان")
        unique_together = [["rfq", "vendor"]]


class RFQVendorResponseLineModel(TenantAwareModel):
    """آیتم پاسخ تأمین‌کننده."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    response = models.ForeignKey(
        RFQVendorResponseModel, on_delete=models.CASCADE,
        related_name="lines", verbose_name=_("پاسخ"),
    )
    rfq_line = models.ForeignKey(
        RFQLineModel, on_delete=models.CASCADE,
        related_name="vendor_response_lines", verbose_name=_("آیتم استعلام"),
    )
    line_number = models.PositiveIntegerField(_("ردیف"), default=0)
    unit_price = models.DecimalField(_("قیمت واحد"), max_digits=20, decimal_places=2, default=0)
    total_price = models.DecimalField(_("مبلغ کل"), max_digits=20, decimal_places=2, default=0)
    delivery_days = models.PositiveIntegerField(_("زمان تحویل (روز)"), default=0)
    notes = models.TextField(_("یادداشت"), blank=True)

    created_at = models.DateTimeField(_("تاریخ ایجاد"), auto_now_add=True)

    class Meta:
        app_label = "scm"
        db_table = "scm_rfq_vendor_response_line"
        verbose_name = _("آیتم پاسخ تأمین‌کننده")
        verbose_name_plural = _("آیتم‌های پاسخ تأمین‌کنندگان")
        ordering = ["line_number"]


# ═══════════════════════════════════════════════════
# 4️⃣  PURCHASE ORDER
# ═══════════════════════════════════════════════════

class PurchaseOrderModel(TenantAwareModel):
    """سفارش خرید."""

    class POStatus(models.TextChoices):
        DRAFT = "DRAFT", _("پیش‌نویس")
        PENDING_APPROVAL = "PENDING_APPROVAL", _("در انتظار تأیید")
        APPROVED = "APPROVED", _("تأیید شده")
        REJECTED = "REJECTED", _("رد شده")
        SENT = "SENT", _("ارسال شده")
        PARTIALLY_RECEIVED = "PARTIALLY_RECEIVED", _("دریافت جزئی")
        FULLY_RECEIVED = "FULLY_RECEIVED", _("دریافت کامل")
        CANCELLED = "CANCELLED", _("لغو شده")
        CLOSED = "CLOSED", _("بسته شده")

    class POPriority(models.TextChoices):
        LOW = "LOW", _("کم")
        NORMAL = "NORMAL", _("عادی")
        HIGH = "HIGH", _("زیاد")
        URGENT = "URGENT", _("فوری")

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    po_number = models.CharField(_("شماره سفارش"), max_length=50, db_index=True)
    title = models.CharField(_("عنوان"), max_length=255, blank=True)
    description = models.TextField(_("توضیحات"), blank=True)
    status = models.CharField(
        _("وضعیت"), max_length=25,
        choices=POStatus.choices, default=POStatus.DRAFT, db_index=True,
    )
    priority = models.CharField(
        _("اولویت"), max_length=10,
        choices=POPriority.choices, default=POPriority.NORMAL,
    )

    # Vendor
    vendor = models.ForeignKey(
        VendorModel, on_delete=models.PROTECT, null=True, blank=True,
        related_name="purchase_orders", verbose_name=_("تأمین‌کننده"),
    )

    # Source
    pr_id = models.UUIDField(_("درخواست خرید"), null=True, blank=True)
    pr_number = models.CharField(_("شماره درخواست خرید"), max_length=50, blank=True)
    rfq_id = models.UUIDField(_("استعلام"), null=True, blank=True)
    rfq_number = models.CharField(_("شماره استعلام"), max_length=50, blank=True)
    contract_id = models.UUIDField(_("قرارداد (CLM)"), null=True, blank=True)

    # Buyer
    buyer_id = models.UUIDField(_("خریدار"), null=True, blank=True)
    buyer_name = models.CharField(_("نام خریدار"), max_length=255, blank=True)

    # Dates
    order_date = models.DateField(_("تاریخ سفارش"), null=True, blank=True)
    expected_delivery_date = models.DateField(_("تاریخ تحویل مورد انتظار"), null=True, blank=True)
    actual_delivery_date = models.DateField(_("تاریخ تحویل واقعی"), null=True, blank=True)

    # Financial
    subtotal = models.DecimalField(_("جمع فرعی"), max_digits=20, decimal_places=2, default=0)
    total_discount = models.DecimalField(_("جمع تخفیف"), max_digits=20, decimal_places=2, default=0)
    total_tax = models.DecimalField(_("جمع مالیات"), max_digits=20, decimal_places=2, default=0)
    total_amount = models.DecimalField(_("مبلغ کل"), max_digits=20, decimal_places=2, default=0)
    currency_code = models.CharField(_("ارز"), max_length=10, default="IRR")

    # Terms
    payment_terms = models.CharField(_("شرایط پرداخت"), max_length=500, blank=True)
    delivery_terms = models.CharField(_("شرایط تحویل"), max_length=500, blank=True)
    shipping_address = models.TextField(_("آدرس تحویل"), blank=True)

    # Approval
    approved_by_id = models.UUIDField(_("تأیید توسط"), null=True, blank=True)
    approved_at = models.DateTimeField(_("تاریخ تأیید"), null=True, blank=True)
    rejection_reason = models.TextField(_("دلیل رد"), blank=True)

    notes = models.TextField(_("یادداشت"), blank=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_purchase_order"
        verbose_name = _("سفارش خرید")
        verbose_name_plural = _("سفارش‌های خرید")
        unique_together = [["tenant", "po_number"]]
        indexes = [
            models.Index(fields=["tenant", "status"]),
            models.Index(fields=["tenant", "vendor"]),
            models.Index(fields=["tenant", "buyer_id"]),
        ]

    def __str__(self):
        return self.po_number


class PurchaseOrderLineModel(TenantAwareModel):
    """آیتم سفارش خرید."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    order = models.ForeignKey(
        PurchaseOrderModel, on_delete=models.CASCADE,
        related_name="lines", verbose_name=_("سفارش خرید"),
    )
    line_number = models.PositiveIntegerField(_("ردیف"), default=0)
    item_id = models.UUIDField(_("کالا"), null=True, blank=True)
    item_code = models.CharField(_("کد کالا"), max_length=50, blank=True)
    item_name = models.CharField(_("نام کالا"), max_length=255, blank=True)
    description = models.TextField(_("توضیحات"), blank=True)
    quantity = models.DecimalField(_("مقدار"), max_digits=18, decimal_places=4, default=0)
    received_quantity = models.DecimalField(
        _("مقدار دریافت‌شده"), max_digits=18, decimal_places=4, default=0,
    )
    returned_quantity = models.DecimalField(
        _("مقدار برگشتی"), max_digits=18, decimal_places=4, default=0,
    )
    uom_id = models.UUIDField(_("واحد"), null=True, blank=True)
    uom_code = models.CharField(_("کد واحد"), max_length=20, blank=True)
    unit_price = models.DecimalField(_("قیمت واحد"), max_digits=20, decimal_places=2, default=0)
    discount_percent = models.DecimalField(
        _("درصد تخفیف"), max_digits=5, decimal_places=2, default=0,
    )
    discount_amount = models.DecimalField(
        _("مبلغ تخفیف"), max_digits=20, decimal_places=2, default=0,
    )
    tax_percent = models.DecimalField(_("درصد مالیات"), max_digits=5, decimal_places=2, default=0)
    tax_amount = models.DecimalField(_("مبلغ مالیات"), max_digits=20, decimal_places=2, default=0)
    line_total = models.DecimalField(_("مبلغ ردیف"), max_digits=20, decimal_places=2, default=0)
    warehouse_id = models.UUIDField(_("انبار مقصد"), null=True, blank=True)
    warehouse_name = models.CharField(_("نام انبار"), max_length=255, blank=True)
    required_date = models.DateField(_("تاریخ نیاز"), null=True, blank=True)
    notes = models.TextField(_("یادداشت"), blank=True)

    pr_line_id = models.UUIDField(_("آیتم درخواست خرید"), null=True, blank=True)
    rfq_response_line_id = models.UUIDField(_("آیتم پاسخ استعلام"), null=True, blank=True)

    created_at = models.DateTimeField(_("تاریخ ایجاد"), auto_now_add=True)
    updated_at = models.DateTimeField(_("تاریخ بروزرسانی"), auto_now=True)

    class Meta:
        app_label = "scm"
        db_table = "scm_purchase_order_line"
        verbose_name = _("آیتم سفارش خرید")
        verbose_name_plural = _("آیتم‌های سفارش خرید")
        ordering = ["line_number"]


# ═══════════════════════════════════════════════════
# 5️⃣  GOODS RECEIPT
# ═══════════════════════════════════════════════════

class GoodsReceiptModel(TenantAwareModel):
    """رسید کالا."""

    class GRStatus(models.TextChoices):
        DRAFT = "DRAFT", _("پیش‌نویس")
        CONFIRMED = "CONFIRMED", _("تأیید شده")
        CANCELLED = "CANCELLED", _("لغو شده")

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    gr_number = models.CharField(_("شماره رسید"), max_length=50, db_index=True)
    status = models.CharField(
        _("وضعیت"), max_length=20,
        choices=GRStatus.choices, default=GRStatus.DRAFT, db_index=True,
    )

    po = models.ForeignKey(
        PurchaseOrderModel, on_delete=models.PROTECT, null=True, blank=True,
        related_name="goods_receipts", verbose_name=_("سفارش خرید"),
    )
    vendor = models.ForeignKey(
        VendorModel, on_delete=models.PROTECT, null=True, blank=True,
        related_name="goods_receipts", verbose_name=_("تأمین‌کننده"),
    )

    receiver_id = models.UUIDField(_("دریافت‌کننده"), null=True, blank=True)
    receiver_name = models.CharField(_("نام دریافت‌کننده"), max_length=255, blank=True)

    receipt_date = models.DateField(_("تاریخ رسید"), null=True, blank=True)
    posting_date = models.DateField(_("تاریخ ثبت"), null=True, blank=True)

    total_amount = models.DecimalField(
        _("مبلغ کل"), max_digits=20, decimal_places=2, default=0,
    )
    currency_code = models.CharField(_("ارز"), max_length=10, default="IRR")

    delivery_note_number = models.CharField(_("شماره بارنامه"), max_length=100, blank=True)
    transporter = models.CharField(_("حمل‌کننده"), max_length=255, blank=True)
    notes = models.TextField(_("یادداشت"), blank=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_goods_receipt"
        verbose_name = _("رسید کالا")
        verbose_name_plural = _("رسیدهای کالا")
        unique_together = [["tenant", "gr_number"]]
        indexes = [models.Index(fields=["tenant", "status"])]

    def __str__(self):
        return self.gr_number


class GoodsReceiptLineModel(TenantAwareModel):
    """آیتم رسید کالا."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    receipt = models.ForeignKey(
        GoodsReceiptModel, on_delete=models.CASCADE,
        related_name="lines", verbose_name=_("رسید کالا"),
    )
    line_number = models.PositiveIntegerField(_("ردیف"), default=0)
    po_line_id = models.UUIDField(_("آیتم سفارش خرید"), null=True, blank=True)
    item_id = models.UUIDField(_("کالا"), null=True, blank=True)
    item_code = models.CharField(_("کد کالا"), max_length=50, blank=True)
    item_name = models.CharField(_("نام کالا"), max_length=255, blank=True)
    ordered_quantity = models.DecimalField(
        _("مقدار سفارش"), max_digits=18, decimal_places=4, default=0,
    )
    received_quantity = models.DecimalField(
        _("مقدار دریافتی"), max_digits=18, decimal_places=4, default=0,
    )
    accepted_quantity = models.DecimalField(
        _("مقدار پذیرفته"), max_digits=18, decimal_places=4, default=0,
    )
    rejected_quantity = models.DecimalField(
        _("مقدار مردود"), max_digits=18, decimal_places=4, default=0,
    )
    uom_id = models.UUIDField(_("واحد"), null=True, blank=True)
    uom_code = models.CharField(_("کد واحد"), max_length=20, blank=True)
    unit_cost = models.DecimalField(_("قیمت واحد"), max_digits=20, decimal_places=2, default=0)
    line_total = models.DecimalField(_("مبلغ ردیف"), max_digits=20, decimal_places=2, default=0)
    warehouse_id = models.UUIDField(_("انبار"), null=True, blank=True)
    warehouse_name = models.CharField(_("نام انبار"), max_length=255, blank=True)
    storage_location_id = models.UUIDField(_("محل نگهداری"), null=True, blank=True)
    batch_number = models.CharField(_("شماره بچ"), max_length=100, blank=True)
    serial_numbers = models.JSONField(_("شماره سریال‌ها"), default=list, blank=True)
    inspection_required = models.BooleanField(_("نیاز به بازرسی"), default=False)
    notes = models.TextField(_("یادداشت"), blank=True)

    created_at = models.DateTimeField(_("تاریخ ایجاد"), auto_now_add=True)
    updated_at = models.DateTimeField(_("تاریخ بروزرسانی"), auto_now=True)

    class Meta:
        app_label = "scm"
        db_table = "scm_goods_receipt_line"
        verbose_name = _("آیتم رسید کالا")
        verbose_name_plural = _("آیتم‌های رسید کالا")
        ordering = ["line_number"]


# ═══════════════════════════════════════════════════
# 6️⃣  PURCHASE RETURN
# ═══════════════════════════════════════════════════

class PurchaseReturnModel(TenantAwareModel):
    """برگشت از خرید."""

    class ReturnStatus(models.TextChoices):
        DRAFT = "DRAFT", _("پیش‌نویس")
        PENDING_APPROVAL = "PENDING_APPROVAL", _("در انتظار تأیید")
        APPROVED = "APPROVED", _("تأیید شده")
        SENT = "SENT", _("ارسال شده")
        COMPLETED = "COMPLETED", _("تکمیل شده")
        CANCELLED = "CANCELLED", _("لغو شده")

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    return_number = models.CharField(_("شماره برگشت"), max_length=50, db_index=True)
    status = models.CharField(
        _("وضعیت"), max_length=25,
        choices=ReturnStatus.choices, default=ReturnStatus.DRAFT, db_index=True,
    )

    po = models.ForeignKey(
        PurchaseOrderModel, on_delete=models.PROTECT, null=True, blank=True,
        related_name="returns", verbose_name=_("سفارش خرید"),
    )
    gr = models.ForeignKey(
        GoodsReceiptModel, on_delete=models.PROTECT, null=True, blank=True,
        related_name="returns", verbose_name=_("رسید کالا"),
    )
    vendor = models.ForeignKey(
        VendorModel, on_delete=models.PROTECT, null=True, blank=True,
        related_name="returns", verbose_name=_("تأمین‌کننده"),
    )

    requester_id = models.UUIDField(_("درخواست‌دهنده"), null=True, blank=True)
    requester_name = models.CharField(_("نام درخواست‌دهنده"), max_length=255, blank=True)

    return_date = models.DateField(_("تاریخ برگشت"), null=True, blank=True)

    total_amount = models.DecimalField(
        _("مبلغ کل"), max_digits=20, decimal_places=2, default=0,
    )
    currency_code = models.CharField(_("ارز"), max_length=10, default="IRR")

    approved_by_id = models.UUIDField(_("تأیید توسط"), null=True, blank=True)
    approved_at = models.DateTimeField(_("تاریخ تأیید"), null=True, blank=True)

    notes = models.TextField(_("یادداشت"), blank=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_purchase_return"
        verbose_name = _("برگشت از خرید")
        verbose_name_plural = _("برگشت‌های از خرید")
        unique_together = [["tenant", "return_number"]]
        indexes = [models.Index(fields=["tenant", "status"])]

    def __str__(self):
        return self.return_number


class PurchaseReturnLineModel(TenantAwareModel):
    """آیتم برگشت از خرید."""

    class ReturnReason(models.TextChoices):
        DEFECTIVE = "DEFECTIVE", _("معیوب")
        WRONG_ITEM = "WRONG_ITEM", _("اشتباه")
        EXCESS_QUANTITY = "EXCESS_QUANTITY", _("مازاد")
        QUALITY_ISSUE = "QUALITY_ISSUE", _("مشکل کیفیت")
        DAMAGED = "DAMAGED", _("آسیب‌دیده")
        OTHER = "OTHER", _("سایر")

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    purchase_return = models.ForeignKey(
        PurchaseReturnModel, on_delete=models.CASCADE,
        related_name="lines", verbose_name=_("برگشت خرید"),
    )
    line_number = models.PositiveIntegerField(_("ردیف"), default=0)
    gr_line_id = models.UUIDField(_("آیتم رسید"), null=True, blank=True)
    po_line_id = models.UUIDField(_("آیتم سفارش خرید"), null=True, blank=True)
    item_id = models.UUIDField(_("کالا"), null=True, blank=True)
    item_code = models.CharField(_("کد کالا"), max_length=50, blank=True)
    item_name = models.CharField(_("نام کالا"), max_length=255, blank=True)
    return_quantity = models.DecimalField(
        _("مقدار برگشتی"), max_digits=18, decimal_places=4, default=0,
    )
    uom_id = models.UUIDField(_("واحد"), null=True, blank=True)
    uom_code = models.CharField(_("کد واحد"), max_length=20, blank=True)
    unit_cost = models.DecimalField(_("قیمت واحد"), max_digits=20, decimal_places=2, default=0)
    line_total = models.DecimalField(_("مبلغ ردیف"), max_digits=20, decimal_places=2, default=0)
    reason = models.CharField(
        _("دلیل برگشت"), max_length=20,
        choices=ReturnReason.choices, default=ReturnReason.OTHER,
    )
    reason_detail = models.TextField(_("توضیح دلیل"), blank=True)
    warehouse_id = models.UUIDField(_("انبار"), null=True, blank=True)
    batch_number = models.CharField(_("شماره بچ"), max_length=100, blank=True)
    serial_numbers = models.JSONField(_("شماره سریال‌ها"), default=list, blank=True)
    notes = models.TextField(_("یادداشت"), blank=True)

    created_at = models.DateTimeField(_("تاریخ ایجاد"), auto_now_add=True)
    updated_at = models.DateTimeField(_("تاریخ بروزرسانی"), auto_now=True)

    class Meta:
        app_label = "scm"
        db_table = "scm_purchase_return_line"
        verbose_name = _("آیتم برگشت از خرید")
        verbose_name_plural = _("آیتم‌های برگشت از خرید")
        ordering = ["line_number"]


# ═══════════════════════════════════════════════════
# 7️⃣  VENDOR EVALUATION
# ═══════════════════════════════════════════════════

class EvaluationCriteriaModel(TenantAwareModel):
    """معیار ارزیابی."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    criteria_code = models.CharField(_("کد"), max_length=50, db_index=True)
    criteria_name = models.CharField(_("نام معیار"), max_length=255)
    description = models.TextField(_("توضیحات"), blank=True)
    weight = models.DecimalField(_("وزن (درصد)"), max_digits=5, decimal_places=2, default=0)
    max_score = models.DecimalField(_("حداکثر امتیاز"), max_digits=5, decimal_places=2, default=100)
    is_active = models.BooleanField(_("فعال"), default=True, db_index=True)

    created_at = models.DateTimeField(_("تاریخ ایجاد"), auto_now_add=True)
    updated_at = models.DateTimeField(_("تاریخ بروزرسانی"), auto_now=True)

    class Meta:
        app_label = "scm"
        db_table = "scm_evaluation_criteria"
        verbose_name = _("معیار ارزیابی")
        verbose_name_plural = _("معیارهای ارزیابی")
        unique_together = [["tenant", "criteria_code"]]


class EvaluationPeriodModel(TenantAwareModel):
    """دوره ارزیابی."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    period_name = models.CharField(_("نام دوره"), max_length=255)
    start_date = models.DateField(_("تاریخ شروع"), null=True, blank=True)
    end_date = models.DateField(_("تاریخ پایان"), null=True, blank=True)
    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_evaluation_period"
        verbose_name = _("دوره ارزیابی")
        verbose_name_plural = _("دوره‌های ارزیابی")

    def __str__(self):
        return self.period_name


class VendorEvaluationModel(TenantAwareModel):
    """ارزیابی تأمین‌کننده."""

    class EvalStatus(models.TextChoices):
        DRAFT = "DRAFT", _("پیش‌نویس")
        IN_PROGRESS = "IN_PROGRESS", _("در حال انجام")
        COMPLETED = "COMPLETED", _("تکمیل شده")
        CANCELLED = "CANCELLED", _("لغو شده")

    class EvalRating(models.TextChoices):
        EXCELLENT = "EXCELLENT", _("عالی")
        GOOD = "GOOD", _("خوب")
        AVERAGE = "AVERAGE", _("متوسط")
        POOR = "POOR", _("ضعیف")
        UNACCEPTABLE = "UNACCEPTABLE", _("غیرقابل قبول")

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    vendor = models.ForeignKey(
        VendorModel, on_delete=models.CASCADE,
        related_name="evaluations", verbose_name=_("تأمین‌کننده"),
    )
    period = models.ForeignKey(
        EvaluationPeriodModel, on_delete=models.CASCADE,
        related_name="evaluations", verbose_name=_("دوره"),
    )
    evaluator_id = models.UUIDField(_("ارزیاب"), null=True, blank=True)
    evaluator_name = models.CharField(_("نام ارزیاب"), max_length=255, blank=True)
    status = models.CharField(
        _("وضعیت"), max_length=20,
        choices=EvalStatus.choices, default=EvalStatus.DRAFT,
    )
    evaluation_date = models.DateField(_("تاریخ ارزیابی"), null=True, blank=True)
    total_score = models.DecimalField(
        _("امتیاز کل"), max_digits=5, decimal_places=2, default=0,
    )
    rating = models.CharField(
        _("رتبه"), max_length=20,
        choices=EvalRating.choices, blank=True,
    )
    comments = models.TextField(_("نظرات"), blank=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_evaluation"
        verbose_name = _("ارزیابی تأمین‌کننده")
        verbose_name_plural = _("ارزیابی‌های تأمین‌کنندگان")
        unique_together = [["tenant", "vendor", "period"]]

    def __str__(self):
        return f"{self.vendor} — {self.period}"


class VendorEvaluationScoreModel(TenantAwareModel):
    """امتیاز ارزیابی per criteria."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    evaluation = models.ForeignKey(
        VendorEvaluationModel, on_delete=models.CASCADE,
        related_name="scores", verbose_name=_("ارزیابی"),
    )
    criteria = models.ForeignKey(
        EvaluationCriteriaModel, on_delete=models.CASCADE,
        related_name="+", verbose_name=_("معیار"),
    )
    weight = models.DecimalField(_("وزن"), max_digits=5, decimal_places=2, default=0)
    score = models.DecimalField(_("امتیاز"), max_digits=5, decimal_places=2, default=0)
    weighted_score = models.DecimalField(
        _("امتیاز وزنی"), max_digits=5, decimal_places=2, default=0,
    )
    comments = models.TextField(_("نظرات"), blank=True)

    class Meta:
        app_label = "scm"
        db_table = "scm_vendor_evaluation_score"
        verbose_name = _("امتیاز ارزیابی")
        verbose_name_plural = _("امتیازهای ارزیابی")


# ═══════════════════════════════════════════════════
# 8️⃣  PRICE MANAGEMENT
# ═══════════════════════════════════════════════════

class VendorPriceListModel(TenantAwareModel):
    """لیست قیمت تأمین‌کننده."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    vendor = models.ForeignKey(
        VendorModel, on_delete=models.CASCADE,
        related_name="price_lists", verbose_name=_("تأمین‌کننده"),
    )
    price_list_name = models.CharField(_("نام لیست قیمت"), max_length=255)
    description = models.TextField(_("توضیحات"), blank=True)
    currency_code = models.CharField(_("ارز"), max_length=10, default="IRR")
    valid_from = models.DateField(_("معتبر از"), null=True, blank=True)
    valid_to = models.DateField(_("معتبر تا"), null=True, 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)

    class Meta:
        app_label = "scm"
        db_table = "scm_vendor_price_list"
        verbose_name = _("لیست قیمت تأمین‌کننده")
        verbose_name_plural = _("لیست قیمت‌های تأمین‌کنندگان")
        indexes = [models.Index(fields=["tenant", "vendor", "is_active"])]

    def __str__(self):
        return f"{self.vendor.vendor_name} — {self.price_list_name}"


class VendorPriceListItemModel(TenantAwareModel):
    """آیتم لیست قیمت."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    price_list = models.ForeignKey(
        VendorPriceListModel, on_delete=models.CASCADE,
        related_name="items", verbose_name=_("لیست قیمت"),
    )
    item_id = models.UUIDField(_("کالا"))
    item_code = models.CharField(_("کد کالا"), max_length=50, blank=True)
    item_name = models.CharField(_("نام کالا"), max_length=255, blank=True)
    uom_id = models.UUIDField(_("واحد"), null=True, blank=True)
    uom_code = models.CharField(_("کد واحد"), max_length=20, blank=True)
    unit_price = models.DecimalField(_("قیمت واحد"), max_digits=20, decimal_places=2, default=0)
    min_quantity = models.DecimalField(
        _("حداقل مقدار"), max_digits=18, decimal_places=4, default=1,
    )
    lead_time_days = models.PositiveIntegerField(_("زمان تحویل (روز)"), default=0)
    notes = models.TextField(_("یادداشت"), blank=True)
    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_price_list_item"
        verbose_name = _("آیتم لیست قیمت")
        verbose_name_plural = _("آیتم‌های لیست قیمت")


class PurchaseDiscountModel(TenantAwareModel):
    """تخفیف خرید."""

    class DiscountType(models.TextChoices):
        PERCENTAGE = "PERCENTAGE", _("درصدی")
        FIXED_AMOUNT = "FIXED_AMOUNT", _("مبلغی")

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    vendor = models.ForeignKey(
        VendorModel, on_delete=models.CASCADE, null=True, blank=True,
        related_name="discounts", verbose_name=_("تأمین‌کننده"),
    )
    item_id = models.UUIDField(_("کالا"), null=True, blank=True)
    item_group_id = models.UUIDField(_("گروه کالا"), null=True, blank=True)
    discount_type = models.CharField(
        _("نوع تخفیف"), max_length=20,
        choices=DiscountType.choices, default=DiscountType.PERCENTAGE,
    )
    discount_value = models.DecimalField(_("مقدار تخفیف"), max_digits=18, decimal_places=4, default=0)
    min_quantity = models.DecimalField(
        _("حداقل مقدار"), max_digits=18, decimal_places=4, default=0,
    )
    min_amount = models.DecimalField(
        _("حداقل مبلغ"), max_digits=20, decimal_places=2, default=0,
    )
    valid_from = models.DateField(_("معتبر از"), null=True, blank=True)
    valid_to = models.DateField(_("معتبر تا"), null=True, blank=True)
    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)

    class Meta:
        app_label = "scm"
        db_table = "scm_purchase_discount"
        verbose_name = _("تخفیف خرید")
        verbose_name_plural = _("تخفیف‌های خرید")
        indexes = [
            models.Index(fields=["tenant", "vendor", "is_active"]),
        ]


# ═══════════════════════════════════════════════════
# 9️⃣  PURCHASE SETTINGS
# ═══════════════════════════════════════════════════

class PurchaseLimitModel(TenantAwareModel):
    """حد مجاز خرید بر اساس نقش."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    role_name = models.CharField(_("نام نقش"), max_length=100)
    max_amount = models.DecimalField(
        _("حداکثر مبلغ سفارش"), max_digits=20, decimal_places=2, default=0,
    )
    currency_code = models.CharField(_("ارز"), max_length=10, default="IRR")
    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_purchase_limit"
        verbose_name = _("حد مجاز خرید")
        verbose_name_plural = _("حدود مجاز خرید")
        unique_together = [["tenant", "role_name"]]
