"""
Developer Payment Models
Tracks all payments made FROM THIS SYSTEM to the developer (PhinTech Solutions Company Ltd).
Integrates with LipiaOnline payment gateway.

© PhinTech Solutions Company Ltd — System v1.0
"""

from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone
import uuid

User = get_user_model()


class DeveloperPayment(models.Model):
    """
    Records every payment initiated from this system to the developer.
    Only payments originating from this system are tracked here —
    payments made directly to the LipiaOnline link by other users are NOT included.
    """

    STATUS_CHOICES = [
        ('pending', 'Pending'),
        ('processing', 'Processing'),
        ('completed', 'Completed'),
        ('failed', 'Failed'),
        ('cancelled', 'Cancelled'),
    ]

    PAYMENT_TYPE_CHOICES = [
        ('maintenance', 'System Maintenance Fee'),
        ('license', 'Software License Fee'),
        ('support', 'Support & Consultation'),
        ('upgrade', 'System Upgrade'),
        ('custom', 'Custom Development'),
        ('other', 'Other'),
    ]

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    # Payment details
    amount = models.DecimalField(max_digits=12, decimal_places=2, help_text="Amount in KES")
    payment_type = models.CharField(max_length=20, choices=PAYMENT_TYPE_CHOICES, default='maintenance')
    description = models.TextField(help_text="Purpose / description of this payment")
    reference = models.CharField(
        max_length=100, unique=True,
        help_text="Unique reference for this payment (auto-generated)"
    )

    # Payer info (the company admin who initiated the payment)
    initiated_by = models.ForeignKey(
        User, on_delete=models.SET_NULL, null=True, blank=True,
        related_name='developer_payments_initiated',
        help_text="Staff member who initiated this payment"
    )
    payer_phone = models.CharField(
        max_length=17,
        help_text="M-Pesa phone number used to complete the payment (company phone)"
    )

    # LipiaOnline / M-Pesa response fields
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending')
    lipia_checkout_id = models.CharField(
        max_length=200, blank=True, null=True,
        help_text="Checkout/request ID returned by LipiaOnline"
    )
    lipia_transaction_id = models.CharField(
        max_length=200, blank=True, null=True,
        help_text="Final transaction ID from LipiaOnline / M-Pesa"
    )
    mpesa_receipt = models.CharField(
        max_length=100, blank=True, null=True,
        help_text="M-Pesa confirmation code (e.g. QHX7XXXXXX)"
    )

    # Raw API responses for audit
    raw_initiation_response = models.JSONField(
        blank=True, null=True,
        help_text="Raw JSON response from LipiaOnline when payment was initiated"
    )
    raw_callback_data = models.JSONField(
        blank=True, null=True,
        help_text="Raw JSON callback/webhook data received from LipiaOnline"
    )

    # Notes
    admin_notes = models.TextField(blank=True, null=True, help_text="Internal notes about this payment")
    failure_reason = models.TextField(blank=True, null=True, help_text="Reason for failure if applicable")

    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    completed_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        db_table = 'developer_payments'
        ordering = ['-created_at']
        verbose_name = 'Developer Payment'
        verbose_name_plural = 'Developer Payments'

    def __str__(self):
        return f"Dev Payment {self.reference} — KES {self.amount} [{self.get_status_display()}]"

    def mark_completed(self, mpesa_receipt=None, transaction_id=None, callback_data=None):
        """Mark this payment as successfully completed."""
        self.status = 'completed'
        self.completed_at = timezone.now()
        if mpesa_receipt:
            self.mpesa_receipt = mpesa_receipt
        if transaction_id:
            self.lipia_transaction_id = transaction_id
        if callback_data:
            self.raw_callback_data = callback_data
        self.save(update_fields=[
            'status', 'completed_at', 'mpesa_receipt',
            'lipia_transaction_id', 'raw_callback_data', 'updated_at'
        ])

    def mark_failed(self, reason=None, callback_data=None):
        """Mark this payment as failed."""
        self.status = 'failed'
        if reason:
            self.failure_reason = reason
        if callback_data:
            self.raw_callback_data = callback_data
        self.save(update_fields=['status', 'failure_reason', 'raw_callback_data', 'updated_at'])

    @property
    def is_completed(self):
        return self.status == 'completed'

    @property
    def is_pending(self):
        return self.status in ('pending', 'processing')
