from django.db import models
from django.utils import timezone
import datetime

class AdminConfig(models.Model):
    private_key = models.CharField(max_length=255, unique=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "Admin Configuration"

class UserSession(models.Model):
    access_code = models.CharField(max_length=6, unique=True)
    phone_number = models.CharField(max_length=20, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"User {self.access_code}"

class GameProject(models.Model):
    GENRE_CHOICES = [
        ('platformer', 'Platformer'),
        ('shooter', 'Top-Down Shooter'),
        ('runner', 'Endless Runner'),
        ('puzzle', 'Puzzle'),
        ('traditional', 'Traditional Script'),
        ('online', 'Online Link'),
    ]

    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    prompt = models.TextField(blank=True)
    genre = models.CharField(max_length=50, choices=GENRE_CHOICES, default='platformer')
    image_reference = models.ImageField(upload_to='game_references/', null=True, blank=True)
    config_json = models.JSONField(default=dict, blank=True)
    script_code = models.TextField(blank=True, help_text="HTML/JS/CSS code for the game")
    external_url = models.URLField(blank=True, null=True, help_text="URL for external online games")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.title

class RentalOption(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    duration_days = models.IntegerField(default=1)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    qr_code_1 = models.ImageField(upload_to='qr_codes/', blank=True, null=True)
    qr_code_2 = models.ImageField(upload_to='qr_codes/', blank=True, null=True)

    def __str__(self):
        return f"{self.title} - {self.price}"

class UserPurchase(models.Model):
    user_session = models.ForeignKey(UserSession, on_delete=models.CASCADE)
    game = models.ForeignKey(GameProject, on_delete=models.CASCADE)
    rental_option = models.ForeignKey(RentalOption, on_delete=models.CASCADE)
    confirmation_code = models.CharField(max_length=12, blank=True, null=True)
    purchased_at = models.DateTimeField(auto_now_add=True)
    expires_at = models.DateTimeField()
    is_paid = models.BooleanField(default=False, help_text="Anti-fraud: Payment detected by intelligent system")
    is_confirmed = models.BooleanField(default=False, help_text="User successfully validated the code")

    def is_valid(self):
        return self.is_confirmed and timezone.now() < self.expires_at

    def __str__(self):
        return f"{self.user_session.access_code} - {self.game.title}"
