"""Bookstore models — used to demo django-shreck's TUI features.

Try these in the shreck shell:
    Book.objects.all()                         # → table view
    Book.objects.filter(price__lt=15)          # → table / detail / compare
    Book.objects.get(pk=1)                     # → detail view
    Author.objects.filter(last_name="Orwell")  # → detail view
"""
from __future__ import annotations

from django.db import models


class Genre(models.Model):
    name = models.CharField(max_length=100, unique=True)
    description = models.TextField(blank=True)

    class Meta:
        ordering = ["name"]

    def __str__(self) -> str:
        return self.name


class Author(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    bio = models.TextField(blank=True)
    born = models.DateField(null=True, blank=True)

    class Meta:
        ordering = ["last_name", "first_name"]

    def __str__(self) -> str:
        return f"{self.first_name} {self.last_name}"


class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books")
    genre = models.ForeignKey(Genre, on_delete=models.SET_NULL, null=True, related_name="books")
    published = models.DateField()
    isbn = models.CharField(max_length=20, unique=True)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    in_stock = models.BooleanField(default=True)

    class Meta:
        ordering = ["title"]

    def __str__(self) -> str:
        return f"{self.title} ({self.author})"


class Order(models.Model):
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="orders")
    quantity = models.PositiveIntegerField(default=1)
    customer_email = models.EmailField()
    ordered_at = models.DateTimeField(auto_now_add=True)
    shipped = models.BooleanField(default=False)

    class Meta:
        ordering = ["-ordered_at"]

    def __str__(self) -> str:
        return f"Order #{self.pk} — {self.book.title} ×{self.quantity}"
