# Generated by Django 4.2.23 on 2025-12-27 00:08

# Django
import django.core.validators
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models

SELL_STATUS_INDEX = models.Index(
    fields=["status", "-created_at"], name="indy_hub_ma_status_cfa62a_idx"
)
SELLER_INDEX = models.Index(
    fields=["seller", "-created_at"], name="indy_hub_ma_seller__c5b878_idx"
)
BUY_STATUS_INDEX = models.Index(
    fields=["status", "-created_at"], name="indy_hub_ma_status_c3e4f4_idx"
)
BUYER_INDEX = models.Index(
    fields=["buyer", "-created_at"], name="indy_hub_ma_buyer_i_6e10d2_idx"
)


def _index_exists(schema_editor, table_name: str, index_name: str) -> bool:
    with schema_editor.connection.cursor() as cursor:
        constraints = schema_editor.connection.introspection.get_constraints(
            cursor, table_name
        )
    return index_name in constraints


def _add_index_if_missing(model, index, schema_editor):
    table = model._meta.db_table
    if not _index_exists(schema_editor, table, index.name):
        schema_editor.add_index(model, index)


def _remove_index_if_exists(model, index, schema_editor):
    table = model._meta.db_table
    if _index_exists(schema_editor, table, index.name):
        schema_editor.remove_index(model, index)


def _add_sell_status_index(apps, schema_editor):
    model = apps.get_model("indy_hub", "MaterialExchangeSellOrder")
    _add_index_if_missing(model, SELL_STATUS_INDEX, schema_editor)


def _remove_sell_status_index(apps, schema_editor):
    model = apps.get_model("indy_hub", "MaterialExchangeSellOrder")
    _remove_index_if_exists(model, SELL_STATUS_INDEX, schema_editor)


def _add_seller_index(apps, schema_editor):
    model = apps.get_model("indy_hub", "MaterialExchangeSellOrder")
    _add_index_if_missing(model, SELLER_INDEX, schema_editor)


def _remove_seller_index(apps, schema_editor):
    model = apps.get_model("indy_hub", "MaterialExchangeSellOrder")
    _remove_index_if_exists(model, SELLER_INDEX, schema_editor)


def _add_buy_status_index(apps, schema_editor):
    model = apps.get_model("indy_hub", "MaterialExchangeBuyOrder")
    _add_index_if_missing(model, BUY_STATUS_INDEX, schema_editor)


def _remove_buy_status_index(apps, schema_editor):
    model = apps.get_model("indy_hub", "MaterialExchangeBuyOrder")
    _remove_index_if_exists(model, BUY_STATUS_INDEX, schema_editor)


def _add_buyer_index(apps, schema_editor):
    model = apps.get_model("indy_hub", "MaterialExchangeBuyOrder")
    _add_index_if_missing(model, BUYER_INDEX, schema_editor)


def _remove_buyer_index(apps, schema_editor):
    model = apps.get_model("indy_hub", "MaterialExchangeBuyOrder")
    _remove_index_if_exists(model, BUYER_INDEX, schema_editor)


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ("indy_hub", "0040_charactersettings_jobs_last_digest_at_and_more"),
    ]

    operations = [
        migrations.CreateModel(
            name="MaterialExchangeConfig",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                (
                    "corporation_id",
                    models.BigIntegerField(
                        help_text="Corporation ID owning the hub hangar"
                    ),
                ),
                (
                    "structure_id",
                    models.BigIntegerField(
                        help_text="Structure or station ID where the hub is located"
                    ),
                ),
                ("structure_name", models.CharField(blank=True, max_length=255)),
                (
                    "hangar_division",
                    models.IntegerField(
                        default=1,
                        help_text="Corp hangar division (1-7)",
                        validators=[
                            django.core.validators.MinValueValidator(1),
                            django.core.validators.MaxValueValidator(7),
                        ],
                    ),
                ),
                (
                    "sell_markup_percent",
                    models.DecimalField(
                        decimal_places=2,
                        default=0,
                        help_text="Markup % on top of Jita Buy when members sell to hub (0 = Jita Buy price)",
                        max_digits=5,
                    ),
                ),
                (
                    "buy_markup_percent",
                    models.DecimalField(
                        decimal_places=2,
                        default=5,
                        help_text="Markup % on top of Jita Buy when members buy from hub",
                        max_digits=5,
                    ),
                ),
                ("last_stock_sync", models.DateTimeField(blank=True, null=True)),
                ("last_price_sync", models.DateTimeField(blank=True, null=True)),
                (
                    "is_active",
                    models.BooleanField(
                        default=True, help_text="Enable/disable the Material Exchange"
                    ),
                ),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
            ],
            options={
                "verbose_name": "Material Exchange Configuration",
                "verbose_name_plural": "Material Exchange Configurations",
            },
        ),
        migrations.CreateModel(
            name="MaterialExchangeSellOrder",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                ("type_id", models.IntegerField(help_text="Material type ID")),
                ("type_name", models.CharField(blank=True, max_length=255)),
                (
                    "quantity",
                    models.BigIntegerField(
                        validators=[django.core.validators.MinValueValidator(1)]
                    ),
                ),
                (
                    "unit_price",
                    models.DecimalField(
                        decimal_places=2,
                        help_text="Price per unit corp pays to member (Jita Buy + markup)",
                        max_digits=20,
                    ),
                ),
                ("total_price", models.DecimalField(decimal_places=2, max_digits=20)),
                (
                    "status",
                    models.CharField(
                        choices=[
                            ("pending", "Pending Approval"),
                            ("approved", "Approved - Awaiting Payment"),
                            ("paid", "Payment Verified"),
                            ("completed", "Completed"),
                            ("rejected", "Rejected"),
                            ("cancelled", "Cancelled"),
                        ],
                        default="pending",
                        max_length=20,
                    ),
                ),
                ("approved_at", models.DateTimeField(blank=True, null=True)),
                ("payment_verified_at", models.DateTimeField(blank=True, null=True)),
                (
                    "payment_journal_ref",
                    models.CharField(
                        blank=True,
                        help_text="ESI wallet journal ref ID if verified",
                        max_length=255,
                    ),
                ),
                ("notes", models.TextField(blank=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_sell_orders",
                        to=settings.AUTH_USER_MODEL,
                    ),
                ),
                (
                    "config",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="sell_orders",
                        to="indy_hub.materialexchangeconfig",
                    ),
                ),
                (
                    "payment_verified_by",
                    models.ForeignKey(
                        blank=True,
                        null=True,
                        on_delete=django.db.models.deletion.SET_NULL,
                        related_name="verified_sell_payments",
                        to=settings.AUTH_USER_MODEL,
                    ),
                ),
                (
                    "seller",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="material_sell_orders",
                        to=settings.AUTH_USER_MODEL,
                    ),
                ),
            ],
            options={
                "verbose_name": "Material Exchange Sell Order",
                "verbose_name_plural": "Material Exchange Sell Orders",
                "ordering": ["-created_at"],
            },
        ),
        migrations.AlterModelOptions(
            name="blueprint",
            options={
                "default_permissions": (),
                "permissions": [
                    ("can_access_indy_hub", "Can access Indy Hub module"),
                    (
                        "can_manage_copy_requests",
                        "Can request or share blueprint copies",
                    ),
                    (
                        "can_manage_corporate_assets",
                        "Can manage corporation blueprints and jobs",
                    ),
                    (
                        "can_manage_material_exchange",
                        "Can manage Material Exchange (approve orders, configure settings)",
                    ),
                ],
                "verbose_name": "Blueprint",
                "verbose_name_plural": "Blueprints",
            },
        ),
        migrations.CreateModel(
            name="MaterialExchangeBuyOrder",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                ("type_id", models.IntegerField(help_text="Material type ID")),
                ("type_name", models.CharField(blank=True, max_length=255)),
                (
                    "quantity",
                    models.BigIntegerField(
                        validators=[django.core.validators.MinValueValidator(1)]
                    ),
                ),
                (
                    "unit_price",
                    models.DecimalField(
                        decimal_places=2,
                        help_text="Price per unit member pays to corp (Jita Buy + markup)",
                        max_digits=20,
                    ),
                ),
                ("total_price", models.DecimalField(decimal_places=2, max_digits=20)),
                (
                    "status",
                    models.CharField(
                        choices=[
                            ("pending", "Pending Approval"),
                            ("approved", "Approved - Awaiting Delivery"),
                            ("delivered", "Delivered"),
                            ("completed", "Completed"),
                            ("rejected", "Rejected"),
                            ("cancelled", "Cancelled"),
                        ],
                        default="pending",
                        max_length=20,
                    ),
                ),
                ("stock_available_at_creation", models.BigIntegerField(default=0)),
                ("approved_at", models.DateTimeField(blank=True, null=True)),
                ("delivered_at", models.DateTimeField(blank=True, null=True)),
                (
                    "delivery_method",
                    models.CharField(
                        blank=True,
                        choices=[
                            ("contract", "Contract"),
                            ("trade", "Direct Trade"),
                            ("hangar", "Corp Hangar Access"),
                        ],
                        max_length=50,
                    ),
                ),
                ("notes", models.TextField(blank=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_buy_orders",
                        to=settings.AUTH_USER_MODEL,
                    ),
                ),
                (
                    "buyer",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="material_buy_orders",
                        to=settings.AUTH_USER_MODEL,
                    ),
                ),
                (
                    "config",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="buy_orders",
                        to="indy_hub.materialexchangeconfig",
                    ),
                ),
                (
                    "delivered_by",
                    models.ForeignKey(
                        blank=True,
                        null=True,
                        on_delete=django.db.models.deletion.SET_NULL,
                        related_name="delivered_buy_orders",
                        to=settings.AUTH_USER_MODEL,
                    ),
                ),
            ],
            options={
                "verbose_name": "Material Exchange Buy Order",
                "verbose_name_plural": "Material Exchange Buy Orders",
                "ordering": ["-created_at"],
            },
        ),
        migrations.CreateModel(
            name="MaterialExchangeTransaction",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                (
                    "transaction_type",
                    models.CharField(
                        choices=[
                            ("sell", "Member Sold to Hub"),
                            ("buy", "Member Bought from Hub"),
                        ],
                        max_length=10,
                    ),
                ),
                ("type_id", models.IntegerField()),
                ("type_name", models.CharField(max_length=255)),
                ("quantity", models.BigIntegerField()),
                ("unit_price", models.DecimalField(decimal_places=2, max_digits=20)),
                ("total_price", models.DecimalField(decimal_places=2, max_digits=20)),
                ("completed_at", models.DateTimeField(auto_now_add=True)),
                (
                    "buy_order",
                    models.OneToOneField(
                        blank=True,
                        null=True,
                        on_delete=django.db.models.deletion.SET_NULL,
                        related_name="transaction",
                        to="indy_hub.materialexchangebuyorder",
                    ),
                ),
                (
                    "config",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="transactions",
                        to="indy_hub.materialexchangeconfig",
                    ),
                ),
                (
                    "sell_order",
                    models.OneToOneField(
                        blank=True,
                        null=True,
                        on_delete=django.db.models.deletion.SET_NULL,
                        related_name="transaction",
                        to="indy_hub.materialexchangesellorder",
                    ),
                ),
                (
                    "user",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="material_transactions",
                        to=settings.AUTH_USER_MODEL,
                    ),
                ),
            ],
            options={
                "verbose_name": "Material Exchange Transaction",
                "verbose_name_plural": "Material Exchange Transactions",
                "ordering": ["-completed_at"],
                "indexes": [
                    models.Index(
                        fields=["transaction_type", "-completed_at"],
                        name="indy_hub_ma_transac_1e3571_idx",
                    ),
                    models.Index(
                        fields=["user", "-completed_at"],
                        name="indy_hub_ma_user_id_c1d3f5_idx",
                    ),
                    models.Index(
                        fields=["type_id", "-completed_at"],
                        name="indy_hub_ma_type_id_731c3d_idx",
                    ),
                ],
            },
        ),
        migrations.CreateModel(
            name="MaterialExchangeStock",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                ("type_id", models.IntegerField(help_text="EVE item type ID")),
                ("type_name", models.CharField(blank=True, max_length=255)),
                ("quantity", models.BigIntegerField(default=0)),
                (
                    "jita_buy_price",
                    models.DecimalField(
                        blank=True, decimal_places=2, default=0, max_digits=20
                    ),
                ),
                (
                    "jita_sell_price",
                    models.DecimalField(
                        blank=True, decimal_places=2, default=0, max_digits=20
                    ),
                ),
                ("last_price_update", models.DateTimeField(blank=True, null=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
                (
                    "config",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="stock_items",
                        to="indy_hub.materialexchangeconfig",
                    ),
                ),
            ],
            options={
                "verbose_name": "Material Exchange Stock",
                "verbose_name_plural": "Material Exchange Stock",
                "indexes": [
                    models.Index(
                        fields=["type_id"], name="indy_hub_ma_type_id_7b1dab_idx"
                    ),
                    models.Index(
                        fields=["config", "type_id"],
                        name="indy_hub_ma_config__05780a_idx",
                    ),
                ],
                "unique_together": {("config", "type_id")},
            },
        ),
        migrations.SeparateDatabaseAndState(
            database_operations=[
                migrations.RunPython(
                    _add_sell_status_index,
                    reverse_code=_remove_sell_status_index,
                )
            ],
            state_operations=[
                migrations.AddIndex(
                    model_name="materialexchangesellorder",
                    index=SELL_STATUS_INDEX,
                )
            ],
        ),
        migrations.SeparateDatabaseAndState(
            database_operations=[
                migrations.RunPython(
                    _add_seller_index,
                    reverse_code=_remove_seller_index,
                )
            ],
            state_operations=[
                migrations.AddIndex(
                    model_name="materialexchangesellorder",
                    index=SELLER_INDEX,
                )
            ],
        ),
        migrations.SeparateDatabaseAndState(
            database_operations=[
                migrations.RunPython(
                    _add_buy_status_index,
                    reverse_code=_remove_buy_status_index,
                )
            ],
            state_operations=[
                migrations.AddIndex(
                    model_name="materialexchangebuyorder",
                    index=BUY_STATUS_INDEX,
                )
            ],
        ),
        migrations.SeparateDatabaseAndState(
            database_operations=[
                migrations.RunPython(
                    _add_buyer_index,
                    reverse_code=_remove_buyer_index,
                )
            ],
            state_operations=[
                migrations.AddIndex(
                    model_name="materialexchangebuyorder",
                    index=BUYER_INDEX,
                )
            ],
        ),
    ]
