"""
SasaPay-specific database models.
These mirror the PHP tables: stkpushresults, b2cpaymentsresults, unknown_payments.
"""

from django.db import models
import uuid


class SasaPayIPNLog(models.Model):
    """Raw IPN payload log — mirrors the old PHP SasaPayIPN.php data capture."""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    raw_data = models.JSONField()
    created_at = models.DateTimeField(auto_now_add=True)

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

    def __str__(self):
        return f"SasaPay IPN {self.id} @ {self.created_at}"


class SasaPaySTKResult(models.Model):
    """
    STK push callback result.
    Mirrors the old PHP stkpushresults table.
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    checkout_request_id = models.CharField(max_length=100, blank=True)
    merchant_loan_ref = models.CharField(max_length=100, blank=True)
    result_code = models.CharField(max_length=20)
    result_desc = models.TextField(blank=True)
    trans_amount = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    created_at = models.DateTimeField(auto_now_add=True)

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

    def __str__(self):
        return f"STK {self.checkout_request_id} — {self.result_code}"

    @property
    def is_success(self):
        return self.result_code == '0'


class SasaPayDisbursementResult(models.Model):
    """
    B2C disbursement callback result.
    Mirrors the old PHP b2cpaymentsresults table.
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    loan_reference = models.CharField(max_length=100, blank=True)
    sasapay_transaction_id = models.CharField(max_length=100, blank=True)
    mpesa_reference = models.CharField(max_length=100, blank=True)
    result_code = models.CharField(max_length=20)
    result_desc = models.TextField(blank=True)
    trans_amount = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    merchant_balance = models.DecimalField(max_digits=14, decimal_places=2, default=0)
    created_at = models.DateTimeField(auto_now_add=True)

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

    def __str__(self):
        return f"Disbursement {self.loan_reference} — {self.result_code}"

    @property
    def is_success(self):
        return self.result_code == '0'


class SasaPayUnknownPayment(models.Model):
    """
    Payments that could not be matched to a borrower.
    Mirrors the old PHP unknown_payments table.
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    amount = models.DecimalField(max_digits=12, decimal_places=2)
    paid_by = models.CharField(max_length=200, blank=True)
    msisdn = models.CharField(max_length=20, blank=True)
    bill_ref = models.CharField(max_length=100, blank=True)
    reference = models.CharField(max_length=100, blank=True)
    notes = models.TextField(blank=True, default='Unrecognised payment')
    resolved = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

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

    def __str__(self):
        return f"Unknown KES {self.amount} from {self.msisdn}"


# ---------------------------------------------------------------------------
# SMS Log — every outgoing SMS is recorded here for admin review
# ---------------------------------------------------------------------------

SMS_TYPE_CHOICES = [
    ('payment_confirmation', 'Payment Confirmation'),
    ('unknown_payment', 'Unknown Payment Alert'),
    ('loan_approval', 'Loan Approval'),
    ('loan_disbursement', 'Loan Disbursement'),
    ('overdue_reminder', 'Overdue Reminder'),
    ('stk_push', 'STK Push Initiated'),
    ('test', 'Test SMS'),
    ('other', 'Other'),
]


class SMSLog(models.Model):
    """
    Audit log of every SMS sent through the system.
    Lets admins see exactly what was sent, to whom, and whether it succeeded.
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    sms_type = models.CharField(max_length=30, choices=SMS_TYPE_CHOICES, default='other')
    recipients = models.TextField(help_text='Comma-separated phone numbers')
    message = models.TextField()
    sender_id = models.CharField(max_length=20, default='HavGrazuri')

    # Delivery status
    status = models.CharField(
        max_length=20,
        choices=[('sent', 'Sent'), ('failed', 'Failed'), ('partial', 'Partial')],
        default='sent'
    )
    at_response = models.JSONField(blank=True, null=True, help_text='Raw Africa\'s Talking API response')
    error_message = models.TextField(blank=True)

    # Context — what triggered this SMS
    loan_number = models.CharField(max_length=30, blank=True)
    borrower_name = models.CharField(max_length=200, blank=True)
    amount = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True)

    created_at = models.DateTimeField(auto_now_add=True)

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

    def __str__(self):
        return f"SMS [{self.sms_type}] to {self.recipients[:30]} @ {self.created_at:%d/%m/%Y %H:%M}"

    @property
    def recipient_count(self):
        return len([r for r in self.recipients.split(',') if r.strip()])

    @property
    def is_success(self):
        return self.status == 'sent'
