from django.contrib.auth.models import User
from django.db import models

from products.models import Product


class Order(models.Model):
    STATUS_CHOICES = (
        ('Pending', 'Pending'),
        ('Paid', 'Paid'),
        ('Shipped', 'Shipped'),
        ('Delivered', 'Delivered'),
    )
    PAYMENT_STATUS_CHOICES = (
        ('Unpaid', 'Unpaid'),
        ('Pending', 'Pending'),
        ('Paid', 'Paid'),
        ('Failed', 'Failed'),
    )
    PAYMENT_PROVIDER_LABELS = {
        'esewa': 'eSewa',
        'khalti': 'Khalti',
        'fonepay': 'Fonepay',
        'stripe': 'Stripe',
        'offline': 'Offline',
    }

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    total_price = models.DecimalField(max_digits=10, decimal_places=2)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='Pending')
    payment_status = models.CharField(max_length=20, choices=PAYMENT_STATUS_CHOICES, default='Unpaid')
    payment_method = models.CharField(max_length=100, default='Pending selection')
    payment_provider = models.CharField(max_length=50, blank=True, default='')
    payment_reference = models.CharField(max_length=255, blank=True, default='')
    payment_session_id = models.CharField(max_length=255, blank=True, default='')
    payment_currency = models.CharField(max_length=10, blank=True, default='NPR')
    paid_at = models.DateTimeField(null=True, blank=True)
    full_name = models.CharField(max_length=150, blank=True, default='')
    phone = models.CharField(max_length=30, blank=True, default='')
    address = models.TextField(blank=True, default='')
    location_label = models.CharField(max_length=255, blank=True, default='')
    latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True)
    longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True)
    location_accuracy_m = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
    delivery_notes = models.CharField(max_length=255, blank=True, default='')

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f"Order #{self.id} - {self.user.username}"

    @property
    def payment_provider_label(self):
        if not self.payment_provider:
            return '-'
        return self.PAYMENT_PROVIDER_LABELS.get(self.payment_provider, self.payment_provider)

    @property
    def has_precise_location(self):
        return self.latitude is not None and self.longitude is not None


class OrderItem(models.Model):
    order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(default=1)
    price = models.DecimalField(max_digits=10, decimal_places=2)

    def __str__(self):
        return f"{self.quantity} x {self.product.name} @ {self.price}"
