from django.db import models
from django.utils import timezone
from django.conf import settings
from product.models import BaseModel, Product
from order.models import OrderPurchase, OrderItem, OrderTransaction
from login_signup.models import User, SoftDeleteManager

class WalletTransaction(BaseModel):
    TRANSACTION_TYPE_CHOICES = [
        ('credit', 'Credit'),
        ('withdraw', 'Withdraw')
    ]
    
    STATUS_CHOICES = [
        ('pending', 'Pending'),
        ('in_progress', 'In Progress'),
        ('completed', 'Completed'),
        ('failed', 'Failed')
    ]
    
    vendor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='wallet_transactions')
    order_purchase = models.ForeignKey(OrderPurchase,on_delete=models.DO_NOTHING,null=True, blank=True,related_name='wallet_transactions')
    order_item = models.ForeignKey(OrderItem, on_delete=models.DO_NOTHING,null=True,blank=True,related_name='wallet_transactions')
    transaction_type = models.CharField(max_length=20,choices=TRANSACTION_TYPE_CHOICES )
    amount = models.DecimalField(max_digits=12,decimal_places=2, blank=True, null=True)
    platform_fee = models.DecimalField(max_digits=16, decimal_places=2, blank=True, null=True)
    vendor_platform_fee = models.DecimalField(max_digits=16, decimal_places=2, blank=True, null=True)
    vendor_total_amount = models.DecimalField(max_digits=16, decimal_places=2, blank=True, null=True)
    status = models.CharField( max_length=20,choices=STATUS_CHOICES)
    description = models.TextField(blank=True, null=True)
    credited_date = models.DateTimeField(null=True, blank=True)
    is_withdraw = models.BooleanField(default=False)

    class Meta:
        db_table = 'wallet_transactions'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.vendor} - {self.transaction_type} - {self.amount}"
    
    
class PayoutRequest(BaseModel):
    STATUS_CHOICES = [
        ('pending', 'Pending'),
        ('approved', 'Approved'),
        ('rejected', 'Rejected'),
        ('failed', 'Failed')
    ]

    PAYMENT_STATUS_CHOICES = [
        ('pending', 'Pending'),
        ('new', 'New'),
        ('processing', 'Processing'),
        ('completed', 'Completed'),
        ('successful', 'Successful'),
        ('failed', 'Failed'),
        ('cancelled', 'Cancelled')
    ]

    PAYMENT_METHOD_CHOICES = [
        ('credit_card', 'Credit Card'),
        ('bank_transfer', 'Bank Transfer'),
        ('bank_account', 'Bank Account'),
        ('mobile_money', 'Mobile Money'),
        ('paypal', 'PayPal')
    ]

    vendor = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='payout_requests'
    )
    amount = models.DecimalField(max_digits=12, decimal_places=2)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending')
    admin_note = models.TextField(blank=True, null=True)
    bank = models.ForeignKey( 'VendorBankDetail',  on_delete=models.DO_NOTHING,  related_name='payout_bank', blank=True, null=True  )
    bank_account_number = models.CharField(max_length=20, blank=True, null=True)
    unique_id = models.CharField(max_length=30, blank=True, null=True)
    requested_date = models.DateTimeField(auto_now_add=True)
    approval_date = models.DateTimeField(null=True, blank=True)
    approved_by = models.ForeignKey(
        User,
        on_delete=models.DO_NOTHING,
        null=True,
        blank=True,
        related_name='approved_payout_requests'
    )
    payment_status = models.CharField(max_length=20, choices=PAYMENT_STATUS_CHOICES, default='pending')
    transaction_id = models.CharField(max_length=255, blank=True, null=True)
    reference_id = models.CharField(max_length=255, blank=True, null=True)
    failed_count = models.IntegerField(default=0)
    payment_method = models.CharField(max_length=20, choices=PAYMENT_METHOD_CHOICES, default='bank_account')
    wallet_ids = models.JSONField(default=list, blank=True, null=True)


    class Meta:
        db_table = 'payout_request'
        ordering = ['-requested_date']

    def __str__(self):
        return f"{self.vendor} - {self.amount} - {self.status}"
    


class VendorBankDetail(BaseModel):

    class PayoutMethod(models.TextChoices):
        BANK_ACCOUNT = 'bank_account', 'Bank Account'
        MOBILE_MONEY = 'mobile_money', 'Mobile Money'

    vendor = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='vendor_bank_details'
    )
    bank_name = models.CharField(max_length=255)
    bank_account_number = models.CharField(max_length=100, blank=True, null=True)
    mobile_account_number = models.CharField(max_length=100, blank=True, null=True)
    mobile_account_bank = models.CharField(max_length=100, blank=True, null=True)
    account_holder_name = models.CharField(max_length=255, blank=True, null=True)
    iban = models.CharField(max_length=255, blank=True, null=True)
    bank_code = models.CharField(max_length=255, blank=True, null=True)
    branch_name = models.CharField(max_length=255, blank=True, null=True)
    branch_address = models.TextField(blank=True, null=True)
    routing_number = models.CharField(max_length=100, blank=True, null=True)
    status = models.BooleanField(default=True)
    transaction_id = models.CharField(max_length=255, blank=True, null=True)
    payout_method = models.CharField(max_length=20, choices=PayoutMethod.choices, default=PayoutMethod.BANK_ACCOUNT)
    mobile_verify = models.BooleanField(default=False)

    class Meta:
        db_table = 'vendor_bank_details'

    def __str__(self):
        return f"{self.vendor} - {self.bank_name}"
    
class WalletBalance(BaseModel):
    
    vendor = models.OneToOneField(User, on_delete=models.CASCADE, related_name="vendor_balance")
    balance = models.DecimalField(max_digits=12, decimal_places=2, default=0.00)
    last_updated = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'wallet_balance'
        indexes = [
            models.Index(fields=['vendor']),
        ]

    def __str__(self):
        return f"{self.vendor.full_name} - Balance: {self.balance}" 
    

class ShoppingPoint(BaseModel):

    class TransactionType(models.TextChoices):
        CREDIT = 'credit', 'Credit'
        DEBIT = 'debit', 'Debit'
   

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='shopping_points')
    transaction_type = models.CharField(max_length=6, choices=TransactionType.choices)
    points = models.PositiveIntegerField()
    description = models.TextField(blank=True, null=True)
    order = models.ForeignKey(OrderPurchase, null=True, blank=True, on_delete=models.SET_NULL, help_text="Order linked to this point transaction")
    source_user = models.ForeignKey(User, null=True, blank=True, related_name='referral_points', on_delete=models.SET_NULL, help_text="User who triggered this referral bonus")

    class Meta:
        db_table = 'shopping_point'
        indexes = [
            models.Index(fields=['user']),
        ]



