# core/models.py
from django.db import models
from django.utils import timezone
from companies.models import Company


# âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
# BRANCH
# âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
class Branch(models.Model):
    """
    A business branch / outlet. In multi-tenant mode each branch belongs to one company.
    """
    company = models.ForeignKey(
        Company,
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='branches',
        db_index=True,
    )
    name = models.CharField(max_length=150)
    code = models.CharField(max_length=50)  # unique_together below
    address = models.TextField(blank=True)
    phone = models.CharField(max_length=30, 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:
        verbose_name = "Branch"
        verbose_name_plural = "Branches"
        ordering = ["name"]
        unique_together = [['company', 'code']]  # code unique per company

    def __str__(self):
        return self.name


# âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
# PROMO CODE / DISCOUNT
# âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
class PromoCode(models.Model):
    DISCOUNT_TYPES = [
        ('percentage', 'Percentage (%)'),
        ('fixed', 'Fixed Amount'),
    ]

    company = models.ForeignKey(
        Company,
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='promo_codes',
        db_index=True,
    )
    code = models.CharField(max_length=50, help_text="The code a cashier enters at checkout")
    description = models.CharField(max_length=200, blank=True)
    discount_type = models.CharField(max_length=15, choices=DISCOUNT_TYPES, default='percentage')
    discount_value = models.DecimalField(
        max_digits=10, decimal_places=2,
        help_text="10 = 10% off (for percentage) or â¦10 off (for fixed)"
    )
    max_uses = models.PositiveIntegerField(
        default=0, help_text="Maximum number of times this code can be used. 0 = unlimited."
    )
    current_uses = models.PositiveIntegerField(default=0)
    is_active = models.BooleanField(default=True)
    expires_at = models.DateField(null=True, blank=True, help_text="Leave blank for no expiry")
    minimum_order_amount = models.DecimalField(
        max_digits=10, decimal_places=2, default=0,
        help_text="Minimum order total for this promo to apply. 0 = no minimum."
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Promo Code'
        verbose_name_plural = 'Promo Codes'
        ordering = ['-created_at']
        unique_together = [['company', 'code']]  # code unique per company

    def __str__(self):
        return f"{self.code} ({self.get_discount_type_display()}: {self.discount_value})"

    @property
    def is_exhausted(self):
        return self.max_uses > 0 and self.current_uses >= self.max_uses

    @property
    def is_expired(self):
        if not self.expires_at:
            return False
        return self.expires_at < timezone.now().date()

    @property
    def is_valid(self):
        return self.is_active and not self.is_expired and not self.is_exhausted

    def calculate_discount(self, order_total):
        """Return the discount amount (Decimal) for a given order total."""
        from decimal import Decimal
        total = Decimal(str(order_total))
        if self.discount_type == 'percentage':
            return (self.discount_value / 100) * total
        else:  # fixed
            return min(self.discount_value, total)  # never give more than the total

# âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
# AI ASSISTANT (Chat & Prompts)
# âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
class AIPrompt(models.Model):
    """
    Predefined questions/prompts for the AI assistant.
    Can be global (for all companies) or specific to one company.
    """
    company = models.ForeignKey(
        Company,
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='ai_prompts',
        help_text="If blank, this is a global prompt for everyone."
    )
    text = models.CharField(max_length=255)
    is_global = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'AI Prompt'
        verbose_name_plural = 'AI Prompts'
        ordering = ['-is_global', '-created_at']

    def __str__(self):
        return f"{'[Global]' if self.is_global else '[Local]'} {self.text}"


class AIChatLog(models.Model):
    """
    Logs of interactions with the AI.
    Used for analytics and rate limiting.
    """
    from django.conf import settings
    
    company = models.ForeignKey(
        Company,
        on_delete=models.CASCADE,
        related_name='ai_chat_logs'
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True
    )
    prompt = models.TextField()
    response = models.TextField()
    tokens_used = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'AI Chat Log'
        verbose_name_plural = 'AI Chat Logs'
        ordering = ['-created_at']

    def __str__(self):
        return f"Chat by {self.user} at {self.created_at}"

# -------------------------------------------------------------
# SITE CONFIGURATION  (Superadmin-only global toggles)
# -------------------------------------------------------------

class SiteConfiguration(models.Model):
    """
    Singleton model for superadmin-controlled global platform settings.
    Use SiteConfiguration.get_solo() to fetch the one instance.
    Features here are globally ON/OFF  they override all company-level flags.
    """
    # -- Payment Gateways --------------------------------------
    GATEWAY_CHOICES = [
        ('monnify',  'Monnify'),
        ('paystack', 'Paystack'),
        ('both',     'Both (company chooses)'),
        ('manual',   'Manual Bank Transfer'),
    ]
    active_payment_gateway = models.CharField(
        max_length=20, choices=GATEWAY_CHOICES, default='monnify',
        help_text='Which payment gateway is used for subscription billing'
    )

    # -- Manual Bank Transfer Details (used when gateway = manual) -----------
    manual_bank_name = models.CharField(
        max_length=100, blank=True,
        help_text='Bank name e.g. "First Bank"',
    )
    manual_account_number = models.CharField(
        max_length=20, blank=True,
        help_text='Account number clients should transfer to',
    )
    manual_account_name = models.CharField(
        max_length=150, blank=True,
        help_text='Account holder name',
    )
    manual_payment_instructions = models.TextField(
        blank=True,
        help_text='Optional extra instructions shown to clients after selecting manual payment. '
                  'e.g. "Send proof of payment to support@swiftpos.ng"',
    )
    manual_whatsapp_number = models.CharField(
        max_length=20, blank=True,
        help_text='WhatsApp number to receive payment proof (include country code e.g. 2348012345678). '
                  'If provided, a WhatsApp button will appear on the checkout page.',
    )

    # -- WhatsApp / SMS Global Toggle -------------------------
    enable_whatsapp = models.BooleanField(
        default=False,
        help_text='Master switch: enables WhatsApp/SMS features for ALL companies. '
                  'Individual companies still need their own API credentials and toggles.'
    )

    # -- Platform Meta -----------------------------------------
    platform_name      = models.CharField(max_length=100, default='SwiftPOS')
    platform_logo_url  = models.CharField(max_length=300, blank=True)
    maintenance_mode   = models.BooleanField(default=False, help_text='Put entire platform in maintenance mode')
    maintenance_message = models.TextField(blank=True, default='SwiftPOS is undergoing scheduled maintenance. We will be back shortly.')

    # -- AI ----------------------------------------------------
    ai_global_daily_limit = models.PositiveIntegerField(default=50, help_text='Platform-wide daily AI chat limit per company')

    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name        = 'Site Configuration'
        verbose_name_plural = 'Site Configuration'

    def __str__(self):
        return f'SwiftPOS Site Configuration (Gateway: {self.get_active_payment_gateway_display()})'

    @classmethod
    def get_solo(cls):
        """Returns the singleton SiteConfiguration instance, creating it if needed."""
        obj, _ = cls.objects.get_or_create(pk=1)
        return obj

