"""
Module Settings — ORM Model (Infrastructure Layer)

مدل Django ORM برای ذخیره‌سازی تنظیمات ماژول‌ها.
از JSONB برای ذخیره‌سازی داینامیک تنظیمات استفاده می‌شود.
"""
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


class ModuleSettingsModel(TenantAwareModel):
    """
    مدل ORM — تنظیمات ماژول per-tenant.

    هر رکورد تنظیمات یک ماژول خاص برای یک tenant خاص را ذخیره می‌کند.
    settings_data به صورت JSONB ذخیره می‌شود و schema-driven است.
    """

    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
    )
    module_key = models.CharField(
        _("کلید ماژول"),
        max_length=100,
        db_index=True,
        help_text=_("شناسه یکتای ماژول (مثلاً hrm, inventory)"),
    )
    settings_data = models.JSONField(
        _("تنظیمات"),
        default=dict,
        blank=True,
        help_text=_("داده‌های تنظیمات به صورت JSON"),
    )

    # Audit fields
    created_at = models.DateTimeField(_("تاریخ ایجاد"), auto_now_add=True)
    updated_at = models.DateTimeField(_("تاریخ بروزرسانی"), auto_now=True)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="created_module_settings",
        verbose_name=_("ایجاد کننده"),
    )
    updated_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="updated_module_settings",
        verbose_name=_("بروزرسانی کننده"),
    )

    class Meta:
        db_table = "plt_module_settings"
        verbose_name = _("تنظیمات ماژول")
        verbose_name_plural = _("تنظیمات ماژول‌ها")
        unique_together = [("tenant", "module_key")]
        indexes = [
            models.Index(
                fields=["tenant", "module_key"],
                name="idx_mod_settings_tenant_key",
            ),
        ]

    def __str__(self):
        return f"Settings: {self.module_key} (Tenant: {self.tenant_id})"
