from django.core.exceptions import ValidationError
from django.db import models

from shop_management.models.base import DataRoot
from shop_management.models.data.shop import Shop
from shop_management.models.data.utils import Currency


class CompanySetting(DataRoot):
    shop = models.OneToOneField(
        Shop,
        on_delete=models.CASCADE,
        related_name="company_setting",
        null=True,
        blank=True,
        help_text="Branch this printable profile and operating policy belongs to.",
    )
    name = models.CharField(max_length=255)
    legal_name = models.CharField(max_length=255, blank=True)
    base_currency = models.ForeignKey(
        Currency,
        on_delete=models.PROTECT,
        related_name="company_settings",
    )
    expiry_warning_days = models.PositiveIntegerField(default=60)
    phone = models.CharField(max_length=100, blank=True)
    email = models.EmailField(blank=True)
    address = models.TextField(blank=True)
    logo = models.ImageField(upload_to="branch_logos/", blank=True, null=True)

    local_name = models.CharField(max_length=255, blank=True)
    agency_name = models.CharField(max_length=255, blank=True)
    invoice_tagline = models.TextField(blank=True)
    contact_person = models.CharField(max_length=255, blank=True)
    facebook = models.CharField(max_length=255, blank=True)
    invoice_footer_note = models.TextField(blank=True)

    invoice_qr_code = models.ImageField(upload_to="branch_invoice_qr/", blank=True, null=True)

    invoice_template = models.CharField(max_length=20, default="auto", choices=[("auto", "Automatic (legacy)"), ("jawid_tasal", "Jawid Tasal"), ("ikhlas", "Ikhlas Poultry Services"), ("jawid_poultry", "Jawid Tasal Poultry Section"), ("jawid_agriculture", "Jawid Tasal Agriculture Section"), ("standard", "Standard")])
    invoice_language = models.CharField(max_length=5, default="en", choices=[("en", "English"), ("dr", "Dari"), ("ps", "Pashto")])
    invoice_direction = models.CharField(max_length=4, default="auto", choices=[("auto", "Automatic"), ("ltr", "Left to right"), ("rtl", "Right to left")])

    class Meta:
        verbose_name = "company setting"
        verbose_name_plural = "company settings"

    def clean(self):
        super().clean()
        if self.shop_id is None and CompanySetting.objects.filter(
            shop__isnull=True
        ).exclude(pk=self.pk).exists():
            raise ValidationError("Only one global fallback company setting is allowed.")

    def save(self, *args, **kwargs):
        self.full_clean()
        return super().save(*args, **kwargs)

    def __str__(self):
        return self.name


class Warehouse(DataRoot):
    shop = models.ForeignKey(
        Shop,
        on_delete=models.PROTECT,
        related_name="warehouses",
    )
    code = models.CharField(max_length=50)
    name = models.CharField(max_length=255)
    address = models.TextField(blank=True)
    is_active = models.BooleanField(default=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["shop", "code"],
                name="uniq_warehouse_code_per_shop",
            )
        ]
        ordering = ["shop_id", "name", "id"]

    def save(self, *args, **kwargs):
        self.code = self.code.strip().upper()
        return super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.shop.name} - {self.name}"
