# commissions\models.py
from django.db import models
from django.conf import settings
from recharge.models import Operator

class CommissionSplit(models.Model):
    order_id = models.CharField(max_length=100, unique=True)
    operator = models.ForeignKey(Operator, on_delete=models.CASCADE)

    vendor_code = models.ForeignKey('VendorCodeMapping', null=True, blank=True, on_delete=models.SET_NULL)

    # Money in rupees
    transaction_amount = models.DecimalField(max_digits=12, decimal_places=2)

    # Provider % can arrive with 3 dp; store it as 3 dp (up to 100.000)
    commission_percent = models.DecimalField(max_digits=6, decimal_places=3)

    # Commission money can be large; keep more headroom + sub-paise precision
    commission_amount = models.DecimalField(max_digits=20, decimal_places=10)


    # Splits (avoid float – keep 10 dp like other buckets)
    gst_amount = models.DecimalField(max_digits=20, decimal_places=10, default=0)
    user_amount = models.DecimalField(max_digits=20, decimal_places=10, default=0)

    referral_user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="ref_commissions"
    )
    referral_amount = models.DecimalField(max_digits=20, decimal_places=10, default=0)

    vendor_refferal_user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="vendor_ref_commissions"
    )
    vendor_refferal_amount = models.DecimalField(max_digits=20, decimal_places=10, default=0)


    pincode = models.CharField(max_length=10)
    pincode_amount  = models.DecimalField(max_digits=20, decimal_places=10)

    district = models.CharField(max_length=100)
    district_amount = models.DecimalField(max_digits=20, decimal_places=10)

    state = models.CharField(max_length=100)
    state_amount    = models.DecimalField(max_digits=20, decimal_places=10)

    vertical = models.CharField(max_length=100)
    vertical_amount = models.DecimalField(max_digits=20, decimal_places=10)

    company_amount  = models.DecimalField(max_digits=20, decimal_places=10)
    tnm_amount      = models.DecimalField(max_digits=20, decimal_places=10)

    credited_on = models.DateTimeField(auto_now_add=True)

    # Totals (ex-GST) – already good
    commission_ex_gst_total   = models.DecimalField(max_digits=20, decimal_places=10, default=0)
    gateway_commission_ex_gst = models.DecimalField(max_digits=20, decimal_places=10, default=0)
    wallet_commission_ex_gst  = models.DecimalField(max_digits=20, decimal_places=10, default=0)

    # Mix (money)
    gateway_amount = models.DecimalField(max_digits=12, decimal_places=2, default=0)  # fine as money
    wallet_amount  = models.DecimalField(max_digits=12, decimal_places=2, default=0)  # fine as money

    class Meta:
        indexes = [
            models.Index(fields=['state']),
            models.Index(fields=['district']),
            models.Index(fields=['pincode']),
            models.Index(fields=['credited_on']),
        ]




    def __str__(self):
        return f"{self.order_id} | INR{self.total_commission():.4f}"

    def total_commission(self):
        return round(
            float(self.gst_amount or 0) +
            float(self.user_amount or 0) +
            float(self.referral_amount or 0) +
            float(self.vendor_refferal_amount or 0) +
            float(self.pincode_amount or 0) +
            float(self.district_amount or 0) +
            float(self.state_amount or 0) +
            float(self.vertical_amount or 0) +
            float(self.company_amount or 0) +
            float(self.tnm_amount or 0), 4
        )

# ✅ Phase 2: Daily Summary Table (For Dashboards)
class CommissionSummary(models.Model):
    WALLET_CHOICES = [
        ('gst', 'GST'),
        ('user', 'User'),
        ('referral', 'Referral'),
        ('vendor_referral', 'Vendor Referral'),
        ('pincode', 'Pincode'),
        ('district', 'District'),
        ('state', 'State'),
        ('vertical', 'Vertical'),
        ('company', 'Company'),
        ('tnm', 'TnM'),
    ]


    date = models.DateField()
    role_type = models.CharField(max_length=20, choices=WALLET_CHOICES)
    location_name = models.CharField(max_length=100)
    location_code = models.CharField(max_length=50)  # e.g. pincode number or state code
    total_amount = models.DecimalField(max_digits=10, decimal_places=4)

    class Meta:
        unique_together = ('date', 'role_type', 'location_code')

    def __str__(self):
        return f"{self.date} | {self.role_type} | {self.location_name} ₹{self.total_amount}"

# ✅ Phase 3: Wallet Role Assignment Mapping

class WalletHeadAssignment(models.Model):
    WALLET_CHOICES = [
        ('pincode', 'Pincode'),
        ('district', 'District'),
        ('state', 'State'),
        ('vertical', 'Vertical'),

    ]

    role_type = models.CharField(max_length=20, choices=WALLET_CHOICES)
    location_code = models.CharField(max_length=50)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    from_date = models.DateField()
    to_date = models.DateField(null=True, blank=True)

    def __str__(self):
        return f"{self.role_type}: {self.location_code} -> {self.user} ({self.from_date} - {self.to_date or 'Present'})"


class Vertical(models.Model):
    name = models.CharField(max_length=100, unique=True)
    description = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

class VendorCodeMapping(models.Model):
    vendor_code = models.CharField(max_length=100, unique=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    referred_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='vendor_referrals')
    vertical = models.ForeignKey(Vertical, on_delete=models.SET_NULL, null=True, blank=True)
    mapped_at = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=True)

    def __str__(self):
        return f"{self.vendor_code} → {self.user.first_name} ({self.vertical})"


class GeoLocation(models.Model):
    pincode = models.CharField(max_length=10, unique=True)
    location_name = models.CharField(max_length=150)
    district = models.CharField(max_length=100)
    state = models.CharField(max_length=100)

    def __str__(self):
        return f"{self.pincode} - {self.location_name}, {self.district}, {self.state}"



class PincodeMonthlySummary(models.Model):
    year = models.IntegerField()
    month = models.IntegerField()  # 1..12
    pincode = models.CharField(max_length=10)
    total_amount = models.DecimalField(max_digits=12, decimal_places=4, default=0)

    class Meta:
        unique_together = ('year', 'month', 'pincode')

    def __str__(self):
        return f"{self.pincode} {self.year}-{self.month:02d} ₹{self.total_amount}"

class PincodeYearlySummary(models.Model):
    year = models.IntegerField()
    pincode = models.CharField(max_length=10)
    total_amount = models.DecimalField(max_digits=12, decimal_places=4, default=0)

    class Meta:
        unique_together = ('year', 'pincode')

    def __str__(self):
        return f"{self.pincode} {self.year} ₹{self.total_amount}"
