from django.db import models
from simple_history.models import HistoricalRecords


class LocationType(models.Model):
    name = models.CharField(max_length=50, unique=True)
    description = models.TextField(blank=True, default="")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    history = HistoricalRecords()

    class Meta:
        ordering = ["name"]
        verbose_name = "Location Type"
        verbose_name_plural = "Location Types"

    def __str__(self):
        return self.name


class Product(models.Model):
    name = models.CharField(max_length=255)
    part_number = models.CharField(max_length=255, blank=True, default="")
    location = models.ForeignKey(
        "Location",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="products_assigned"
    )
    description = models.TextField(blank=True, default="")
    min_stock_level = models.IntegerField(default=1)
    note = models.CharField(max_length=255, blank=True, default="")
    tags = models.ManyToManyField("Tag", blank=True, related_name="products")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    history = HistoricalRecords()

    class Meta:
        ordering = ["name"]

    def __str__(self):
        return self.name


class Tag(models.Model):
    tag_id = models.CharField(max_length=255, unique=True)
    note = models.CharField(max_length=255, blank=True, default="")
    created_at = models.DateTimeField(auto_now_add=True)
    history = HistoricalRecords()

    class Meta:
        ordering = ["tag_id"]

    def __str__(self):
        return self.tag_id


class Location(models.Model):
    code = models.CharField(max_length=64)
    name = models.CharField(max_length=255)
    description = models.TextField(blank=True, default="")
    parent = models.ForeignKey(
        "self",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="children",
        help_text="Parent location (leave empty for root)"
    )
    type = models.ForeignKey(
        "LocationType",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="locations",
        help_text="Optional type for this location"
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    history = HistoricalRecords()

    class Meta:
        ordering = ["code"]

    def __str__(self):
        return f"{self.code} ({self.name})"


class Sighting(models.Model):
    tag_id = models.CharField(max_length=64)
    loc = models.CharField(max_length=64)
    seen_at = models.DateTimeField()
    signal = models.IntegerField()
    batch_ts = models.DateTimeField()

    class Meta:
        managed = False
        db_table = "sightings"
        ordering = ["-seen_at"]

    def __str__(self):
        return f"{self.tag_id} @ {self.loc}"
