import uuid
from django.db import models
from django.contrib.auth.models import User
from django.utils.text import slugify
from core.models import TimeStampedModel


class Business(TimeStampedModel):
    """
    A business account on the platform. Created atomically upon successful
    booking payment verification. Owns Products and Sales.
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, related_name='business'
    )
    name = models.CharField(max_length=200)
    slug = models.SlugField(max_length=220, unique=True)
    logo = models.ImageField(upload_to='businesses/logos/', blank=True, null=True)
    phone = models.CharField(max_length=20)
    email = models.EmailField()
    is_verified = models.BooleanField(
        default=False,
        help_text='Admin-controlled. Drives the Trusted Businesses wall on the landing page.'
    )
    # Payout details (Mobile Money / Bank Account via Paystack Subaccount)
    payout_provider = models.CharField(max_length=100, blank=True, help_text='Bank or Mobile Money Provider (MTN, Telecel, GCB, etc.)')
    payout_account_number = models.CharField(max_length=50, blank=True, help_text='Phone number or Bank account number')
    payout_account_name = models.CharField(max_length=200, blank=True, help_text='Name registered on account')
    payout_bank_code = models.CharField(max_length=20, blank=True, help_text='Paystack bank/momo code')
    paystack_subaccount_code = models.CharField(max_length=100, blank=True, help_text='Paystack Subaccount Code (e.g. ACCT_xxx)')
    
    @property
    def is_payout_configured(self):
        return bool(self.paystack_subaccount_code and self.payout_account_number)
    class Meta:
        verbose_name_plural = 'Businesses'
        ordering = ['-created_at']

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.slug:
            base_slug = slugify(self.name)
            slug = base_slug
            counter = 1
            while Business.objects.filter(slug=slug).exists():
                slug = f"{base_slug}-{counter}"
                counter += 1
            self.slug = slug
        super().save(*args, **kwargs)

    @property
    def has_sales(self):
        return self.sales.exists()

class DeliveryOption(TimeStampedModel):
    """
    Delivery options defined by a business (e.g. Within Accra - GHS 0 - Includes Nungua, Osu).
    Selected by buyers during guest checkout.
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    business = models.ForeignKey(
        Business, on_delete=models.CASCADE, related_name='delivery_options'
    )
    name = models.CharField(max_length=200, help_text='Region or delivery name (e.g., Within Accra)')
    fee = models.DecimalField(
        max_digits=10, decimal_places=2, default=0.00,
        help_text='Delivery price in GHS (0.00 for free delivery)'
    )
    description = models.TextField(
        blank=True,
        help_text='Coverage area notes (e.g., Includes Nungua, Osu, Spintex, East Legon)'
    )
    is_active = models.BooleanField(default=True)
    order = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ['order', 'fee', 'created_at']

    def __str__(self):
        fee_str = "Free" if self.fee == 0 else f"GHS {self.fee}"
        return f"{self.name} ({fee_str})"