import django.db.models.deletion
import inventory.models
from decimal import Decimal
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ("catalog_app", "0025_book_author_inventory_fields"),
        ("store", "0004_order_paybill_proof"),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        # ── StockLocation ────────────────────────────────────────────────────
        migrations.CreateModel(
            name="StockLocation",
            fields=[
                ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
                ("name", models.CharField(max_length=255)),
                ("code", models.CharField(db_index=True, max_length=20, unique=True)),
                ("location_type", models.CharField(choices=[("warehouse","Main Warehouse"),("office","Office"),("depot","Depot"),("bookstore","Bookstore"),("event","Event"),("author","Author"),("damaged","Damaged Stock"),("other","Other")], max_length=30)),
                ("address", models.TextField(blank=True)),
                ("is_active", models.BooleanField(default=True)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
            ],
            options={"ordering": ["name"], "verbose_name": "Stock Location", "verbose_name_plural": "Stock Locations"},
        ),
        # ── Bookstore ────────────────────────────────────────────────────────
        migrations.CreateModel(
            name="Bookstore",
            fields=[
                ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
                ("name", models.CharField(max_length=255)),
                ("contact_person", models.CharField(blank=True, max_length=255)),
                ("phone", models.CharField(blank=True, max_length=20)),
                ("email", models.EmailField(blank=True)),
                ("address", models.TextField(blank=True)),
                ("is_active", models.BooleanField(default=True)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
                ("stock_location", models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="bookstore", to="inventory.stocklocation")),
            ],
            options={"ordering": ["name"], "verbose_name": "Bookstore", "verbose_name_plural": "Bookstores"},
        ),
        # ── Event ────────────────────────────────────────────────────────────
        migrations.CreateModel(
            name="Event",
            fields=[
                ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
                ("name", models.CharField(max_length=255)),
                ("venue", models.CharField(max_length=255)),
                ("start_date", models.DateField(db_index=True)),
                ("end_date", models.DateField()),
                ("notes", models.TextField(blank=True)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("stock_location", models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="event", to="inventory.stocklocation")),
            ],
            options={"ordering": ["-start_date"], "verbose_name": "Event / Book Fair", "verbose_name_plural": "Events / Book Fairs"},
        ),
        # ── InventoryTransaction ─────────────────────────────────────────────
        migrations.CreateModel(
            name="InventoryTransaction",
            fields=[
                ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
                ("quantity", models.PositiveIntegerField()),
                ("transaction_type", models.CharField(choices=[("receipt_from_author","Receipt from Author"),("transfer","Internal Transfer"),("dispatch_to_bookstore","Dispatch to Bookstore"),("dispatch_to_event","Dispatch to Event"),("return_from_bookstore","Return from Bookstore"),("return_from_event","Return from Event"),("write_off","Write Off"),("adjustment","Stock Adjustment"),("sale","Sale"),("reversal","Reversal")], db_index=True, max_length=30)),
                ("transaction_reference", models.CharField(blank=True, db_index=True, max_length=100)),
                ("is_reversed", models.BooleanField(default=False)),
                ("notes", models.TextField(blank=True)),
                ("created_at", models.DateTimeField(auto_now_add=True, db_index=True)),
                ("book", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="inventory_transactions", to="catalog_app.book")),
                ("destination_location", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="incoming_transactions", to="inventory.stocklocation")),
                ("performed_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="inventory_transactions", to=settings.AUTH_USER_MODEL)),
                ("reversed_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="reverses", to="inventory.inventorytransaction")),
                ("source_location", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="outgoing_transactions", to="inventory.stocklocation")),
            ],
            options={"ordering": ["-created_at"], "verbose_name": "Inventory Transaction", "verbose_name_plural": "Inventory Transactions"},
        ),
        migrations.AddIndex(model_name="inventorytransaction", index=models.Index(fields=["book", "created_at"], name="inv_tx_book_date_idx")),
        migrations.AddIndex(model_name="inventorytransaction", index=models.Index(fields=["transaction_type", "created_at"], name="inv_tx_type_date_idx")),
        # ── InventoryBalance ─────────────────────────────────────────────────
        migrations.CreateModel(
            name="InventoryBalance",
            fields=[
                ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
                ("quantity_on_hand", models.IntegerField(default=0)),
                ("quantity_reserved", models.IntegerField(default=0)),
                ("book", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="inventory_balances", to="catalog_app.book")),
                ("location", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="inventory_balances", to="inventory.stocklocation")),
            ],
            options={"verbose_name": "Inventory Balance", "verbose_name_plural": "Inventory Balances"},
        ),
        migrations.AlterUniqueTogether(name="inventorybalance", unique_together={("book", "location")}),
        migrations.AddIndex(model_name="inventorybalance", index=models.Index(fields=["book"], name="inv_bal_book_idx")),
        migrations.AddIndex(model_name="inventorybalance", index=models.Index(fields=["location"], name="inv_bal_loc_idx")),
        # ── Sale ─────────────────────────────────────────────────────────────
        migrations.CreateModel(
            name="Sale",
            fields=[
                ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
                ("invoice_number", models.CharField(db_index=True, default=inventory.models._generate_invoice_number, max_length=30, unique=True)),
                ("sale_channel", models.CharField(choices=[("website","Website"),("bookstore","Bookstore"),("event","Event / Book Fair"),("whatsapp","WhatsApp"),("phone","Phone"),("walk_in","Walk-in"),("direct","Direct"),("bulk","Bulk Order"),("other","Other")], db_index=True, max_length=30)),
                ("customer_name", models.CharField(blank=True, max_length=255)),
                ("customer_phone", models.CharField(blank=True, max_length=20)),
                ("sale_date", models.DateField(db_index=True)),
                ("total_gross", models.DecimalField(decimal_places=2, default=Decimal("0"), max_digits=12)),
                ("total_discount", models.DecimalField(decimal_places=2, default=Decimal("0"), max_digits=12)),
                ("total_net", models.DecimalField(decimal_places=2, default=Decimal("0"), max_digits=12)),
                ("total_profit", models.DecimalField(decimal_places=2, default=Decimal("0"), max_digits=12)),
                ("total_author_payout", models.DecimalField(decimal_places=2, default=Decimal("0"), max_digits=12)),
                ("notes", models.TextField(blank=True)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
                ("bookstore", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="sales", to="inventory.bookstore")),
                ("event", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="sales", to="inventory.event")),
                ("linked_order", models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="inventory_sale", to="store.order")),
                ("recorded_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="recorded_sales", to=settings.AUTH_USER_MODEL)),
            ],
            options={"ordering": ["-sale_date", "-created_at"], "verbose_name": "Sale", "verbose_name_plural": "Sales"},
        ),
        migrations.AddIndex(model_name="sale", index=models.Index(fields=["sale_date", "sale_channel"], name="inv_sale_date_channel_idx")),
        # ── SaleItem ─────────────────────────────────────────────────────────
        migrations.CreateModel(
            name="SaleItem",
            fields=[
                ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
                ("quantity", models.PositiveIntegerField()),
                ("unit_price", models.DecimalField(decimal_places=2, max_digits=10)),
                ("discount_percent", models.DecimalField(decimal_places=2, default=Decimal("0"), max_digits=5)),
                ("gross_amount", models.DecimalField(decimal_places=2, max_digits=12)),
                ("discount_amount", models.DecimalField(decimal_places=2, max_digits=12)),
                ("net_amount", models.DecimalField(decimal_places=2, max_digits=12)),
                ("my_keep_percent", models.DecimalField(decimal_places=2, max_digits=5)),
                ("author_pay_percent", models.DecimalField(decimal_places=2, max_digits=5)),
                ("my_profit_amount", models.DecimalField(decimal_places=2, max_digits=12)),
                ("author_payout_amount", models.DecimalField(decimal_places=2, max_digits=12)),
                ("payout_included", models.BooleanField(db_index=True, default=False)),
                ("book", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="sale_items", to="catalog_app.book")),
                ("sale", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="items", to="inventory.sale")),
                ("stock_location", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="sale_items", to="inventory.stocklocation")),
            ],
            options={"ordering": ["id"], "verbose_name": "Sale Item", "verbose_name_plural": "Sale Items"},
        ),
        migrations.AddIndex(model_name="saleitem", index=models.Index(fields=["book", "payout_included"], name="inv_saleitem_book_payout_idx")),
        # ── AuthorPayout ─────────────────────────────────────────────────────
        migrations.CreateModel(
            name="AuthorPayout",
            fields=[
                ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
                ("period_type", models.CharField(choices=[("monthly","Monthly"),("quarterly","Quarterly"),("custom","Custom")], max_length=20)),
                ("period_start", models.DateField()),
                ("period_end", models.DateField()),
                ("total_earnings", models.DecimalField(decimal_places=2, max_digits=12)),
                ("total_adjustments", models.DecimalField(decimal_places=2, default=Decimal("0"), max_digits=12)),
                ("total_paid", models.DecimalField(decimal_places=2, default=Decimal("0"), max_digits=12)),
                ("outstanding_balance", models.DecimalField(decimal_places=2, max_digits=12)),
                ("status", models.CharField(choices=[("pending","Pending"),("approved","Approved"),("paid","Paid"),("cancelled","Cancelled")], db_index=True, default="pending", max_length=20)),
                ("payment_method", models.CharField(blank=True, max_length=100)),
                ("payment_reference", models.CharField(blank=True, max_length=100)),
                ("payment_date", models.DateField(blank=True, null=True)),
                ("notes", models.TextField(blank=True)),
                ("approved_at", models.DateTimeField(blank=True, null=True)),
                ("paid_at", models.DateTimeField(blank=True, null=True)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
                ("approved_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="approved_payouts", to=settings.AUTH_USER_MODEL)),
                ("author", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="payouts", to="catalog_app.author")),
                ("prepared_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="prepared_payouts", to=settings.AUTH_USER_MODEL)),
            ],
            options={"ordering": ["-period_end", "author"], "verbose_name": "Author Payout", "verbose_name_plural": "Author Payouts"},
        ),
        migrations.AddIndex(model_name="authorpayout", index=models.Index(fields=["author", "status"], name="inv_payout_author_status_idx")),
        migrations.AddIndex(model_name="authorpayout", index=models.Index(fields=["period_start", "period_end"], name="inv_payout_period_idx")),
        # ── AuthorPayoutItem ─────────────────────────────────────────────────
        migrations.CreateModel(
            name="AuthorPayoutItem",
            fields=[
                ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
                ("gross_earnings", models.DecimalField(decimal_places=2, max_digits=12)),
                ("adjustment_amount", models.DecimalField(decimal_places=2, default=Decimal("0"), max_digits=12)),
                ("adjustment_notes", models.TextField(blank=True)),
                ("net_earnings", models.DecimalField(decimal_places=2, max_digits=12)),
                ("book", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="payout_items", to="catalog_app.book")),
                ("payout", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="items", to="inventory.authorpayout")),
                ("sale_item", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="payout_items", to="inventory.saleitem")),
            ],
            options={"ordering": ["book__title"], "verbose_name": "Payout Item", "verbose_name_plural": "Payout Items"},
        ),
        # ── ExpenseCategory ──────────────────────────────────────────────────
        migrations.CreateModel(
            name="ExpenseCategory",
            fields=[
                ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
                ("name", models.CharField(max_length=100, unique=True)),
                ("description", models.TextField(blank=True)),
            ],
            options={"ordering": ["name"], "verbose_name": "Expense Category", "verbose_name_plural": "Expense Categories"},
        ),
        # ── Expense ──────────────────────────────────────────────────────────
        migrations.CreateModel(
            name="Expense",
            fields=[
                ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
                ("amount", models.DecimalField(decimal_places=2, max_digits=12)),
                ("date", models.DateField(db_index=True)),
                ("description", models.TextField()),
                ("notes", models.TextField(blank=True)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("category", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="expenses", to="inventory.expensecategory")),
                ("linked_book", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="expenses", to="catalog_app.book")),
                ("linked_event", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="expenses", to="inventory.event")),
                ("linked_sale", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="expenses", to="inventory.sale")),
                ("receipt_image", models.FileField(blank=True, null=True, upload_to="expense_receipts/")),
                ("recorded_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="recorded_expenses", to=settings.AUTH_USER_MODEL)),
            ],
            options={"ordering": ["-date", "-created_at"], "verbose_name": "Expense", "verbose_name_plural": "Expenses"},
        ),
        migrations.AddIndex(model_name="expense", index=models.Index(fields=["date", "category"], name="inv_expense_date_cat_idx")),
        # ── AuditLog ─────────────────────────────────────────────────────────
        migrations.CreateModel(
            name="AuditLog",
            fields=[
                ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
                ("action", models.CharField(choices=[("CREATE","Create"),("UPDATE","Update"),("DELETE","Delete"),("APPROVE","Approve"),("REJECT","Reject"),("PAY","Pay"),("REVERSE","Reverse")], db_index=True, max_length=20)),
                ("model_name", models.CharField(db_index=True, max_length=100)),
                ("object_id", models.CharField(max_length=50)),
                ("object_repr", models.CharField(max_length=500)),
                ("old_values", models.JSONField(blank=True, null=True)),
                ("new_values", models.JSONField(blank=True, null=True)),
                ("ip_address", models.GenericIPAddressField(blank=True, null=True)),
                ("timestamp", models.DateTimeField(auto_now_add=True, db_index=True)),
                ("user", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="inventory_audit_logs", to=settings.AUTH_USER_MODEL)),
            ],
            options={"ordering": ["-timestamp"], "verbose_name": "Audit Log", "verbose_name_plural": "Audit Logs"},
        ),
        migrations.AddIndex(model_name="auditlog", index=models.Index(fields=["model_name", "object_id"], name="inv_audit_model_obj_idx")),
        migrations.AddIndex(model_name="auditlog", index=models.Index(fields=["user", "timestamp"], name="inv_audit_user_ts_idx")),
    ]
