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 AIChatHistory(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE, 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"
        indexes = [
            models.Index(fields=['chat_title']),
            # We'll use database-level full-text search or icontains for now
        ]

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