import uuid
from django.db import models
from django.contrib.postgres.fields import JSONField

class DrfRequestLog(models.Model):
    """Logs Django rest framework API requests"""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4)
    user = models.ForeignKey(
        'system.user',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )
    requested_at = models.DateTimeField(db_index=True)
    response_ms = models.PositiveIntegerField(default=0)
    path = models.CharField(
        max_length=400,
        db_index=True,
        help_text="请求地址",
    )
    view = models.CharField(
        max_length=400,
        null=True,
        blank=True,
        db_index=True,
        help_text="执行视图",
    )
    view_method = models.CharField(
        max_length=20,
        null=True,
        blank=True,
        db_index=True,
    )
    remote_addr = models.GenericIPAddressField()
    host = models.URLField()
    method = models.CharField(max_length=10)
    query_params = JSONField(null=True, blank=True)
    data = JSONField(null=True, blank=True)
    response = JSONField(null=True, blank=True)
    errors = models.TextField(null=True, blank=True)
    agent = models.TextField(null=True, blank=True)
    status_code = models.PositiveIntegerField(null=True, blank=True, db_index=True)

    class Meta:
        verbose_name = "DRF请求日志"

    def __str__(self):
        return "{} {}".format(self.method, self.path)
