from uuid import uuid4

from django.db import models


class Loan(models.Model):
    """
    Model for book loans.

    """

    uuid = models.UUIDField(default=uuid4, db_index=True, verbose_name="UUID")
    person = models.ForeignKey("library.Person", on_delete=models.CASCADE, related_name="loans", verbose_name="person")
    book = models.ForeignKey("library.Book", on_delete=models.CASCADE, related_name="loans", verbose_name="book")
    date = models.DateTimeField(auto_now_add=True, verbose_name="date")
    expected_return = models.DateTimeField(null=True, verbose_name="expected return date")
    borrowed = models.BooleanField(null=True, default=True, verbose_name="borrowed")

    class Meta:
        verbose_name = "book loan"
        verbose_name_plural = "book loans"
        unique_together = [("book", "borrowed")]

    def __str__(self):
        return f"Book loan: {self.person} → {self.book}"

    def return_book(self):
        self.borrowed = None
        self.save()
