# apps/usage/models.py
from django.db import models
from django.utils import timezone
from apps.apps_.models import APIKey
from apps.companies.models import Company


class UsageLog(models.Model):
    api_key = models.ForeignKey(APIKey, on_delete=models.SET_NULL, null=True, blank=True)
    company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True, blank=True, related_name="usage_logs")

    endpoint_name = models.CharField(max_length=100, blank=True, null=True)
    path = models.CharField(max_length=255)
    method = models.CharField(max_length=10)
    status_code = models.IntegerField(null=True, blank=True)

    weight = models.IntegerField(default=1)  # how much this request counts against quota
    timestamp = models.DateTimeField(default=timezone.now)

    class Meta:
        indexes = [
            models.Index(fields=["company", "timestamp"]),
        ]

    def __str__(self):
        company_name = self.company.name if self.company else "NoCompany"
        endpoint = self.endpoint_name or self.path
        return f"{company_name} - {endpoint} ({self.timestamp})"
