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

class Company(models.Model):
    name = models.CharField(max_length=255)
    tenant_id = models.SlugField(unique=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='members')
    role = models.CharField(max_length=50, choices=[('admin', 'Admin'), ('user', 'End-User')], default='user')

    def __str__(self):
        return f"{self.user.username} ({self.company.name})"

class AIConfiguration(models.Model):
    PROVIDER_CHOICES = [
        ('openai', 'OpenAI'),
        ('perplexity', 'Perplexity'),
        ('merlin', 'Merlin AI'),
        ('poe', 'POE'),
        ('openrouter', 'OpenRouter (Free Tiers)'),
    ]
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='ai_configs')
    provider = models.CharField(max_length=50, choices=PROVIDER_CHOICES)
    api_key = models.CharField(max_length=512)  # Stored encrypted
    is_active = models.BooleanField(default=True)
    last_sync = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.company.name} - {self.get_provider_display()}"

class AIChatHistory(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='chat_histories')
    ai_configuration = models.ForeignKey(AIConfiguration, on_delete=models.SET_NULL, null=True, blank=True, related_name='chat_histories')
    ai_chat_engine = models.CharField(max_length=100)  # ChatGPT, Bing, etc.
    ai_chat_id = models.CharField(max_length=255)
    chat_title = models.CharField(max_length=512)
    chat_content = models.TextField()
    chat_last_date = models.DateTimeField()
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = "AI Chat Histories"
        ordering = ['-chat_last_date']
        unique_together = ('company', 'ai_chat_id')
        indexes = [
            models.Index(fields=['chat_title']),
        ]

    def __str__(self):
        return f"[{self.ai_chat_engine}] {self.chat_title}"

class SyncHistoryLog(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    configuration = models.ForeignKey(AIConfiguration, on_delete=models.CASCADE)
    status = models.CharField(max_length=50, choices=[('success', 'Success'), ('error', 'Error')])
    records_synced = models.IntegerField(default=0)
    error_message = models.TextField(null=True, blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.timestamp} - {self.company.name} ({self.status})"
