<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Migration;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\DB\Types;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;

/**
 * Migration: Create inventory tracking tables.
 *
 * Creates the following tables:
 * - mv_inventory_categories — Category registry
 * - mv_inventory_item_categories — Join table (item ↔ category)
 * - mv_inventory_general_material — General material items
 * - mv_inventory_stock_items — Stock / sales items
 * - mv_inventory_stock_variants — Variant options per stock item
 * - mv_inventory_sales — Sale records (audit trail)
 */
class Version000018Date20260421000000 extends SimpleMigrationStep {

    public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
        /** @var ISchemaWrapper $schema */
        $schema = $schemaClosure();

        // ── mv_inventory_categories (no FKs, create first) ───────────
        if (!$schema->hasTable('mv_inventory_categories')) {
            $table = $schema->createTable('mv_inventory_categories');
            $table->addColumn('id', 'bigint', [
                'autoincrement' => true,
                'notnull' => true,
                'length' => 8,
            ]);
            $table->addColumn('name', 'string', [
                'notnull' => true,
                'length' => 100,
                'default' => '',
            ]);
            $table->addColumn('created_at', 'datetime', [
                'notnull' => false,
                'default' => null,
            ]);
            $table->setPrimaryKey(['id']);
            $table->addUniqueIndex(['name'], 'inventory_cat_name_uindex');
        } else {
            $table = $schema->getTable('mv_inventory_categories');
            if (!$table->hasColumn('created_at')) {
                $table->addColumn('created_at', 'datetime', [
                    'notnull' => false,
                    'default' => null,
                ]);
            }
            if (!$table->hasIndex('inventory_cat_name_uindex')) {
                $table->addUniqueIndex(['name'], 'inventory_cat_name_uindex');
            }
        }

        // ── mv_inventory_general_material (referenced by item_categories) ──
        if (!$schema->hasTable('mv_inventory_general_material')) {
            $table = $schema->createTable('mv_inventory_general_material');
            $table->addColumn('id', 'bigint', [
                'autoincrement' => true,
                'notnull' => true,
                'length' => 8,
            ]);
            $table->addColumn('name', 'string', [
                'notnull' => true,
                'length' => 255,
                'default' => '',
            ]);
            $table->addColumn('condition', Types::INTEGER, [
                'notnull' => false,
                'default' => null,
                'unsigned' => true,
            ]);
            $table->addColumn('notes', 'text', [
                'notnull' => false,
                'default' => null,
                'length' => 65535,
            ]);
            $table->addColumn('created_at', 'datetime', [
                'notnull' => true,
                'default' => '1970-01-01 00:00:00',
            ]);
            $table->addColumn('updated_at', 'datetime', [
                'notnull' => true,
                'default' => '1970-01-01 00:00:00',
            ]);
            $table->setPrimaryKey(['id']);
        }

        // ── mv_inventory_stock_items (referenced by stock_variants & sales) ──
        if (!$schema->hasTable('mv_inventory_stock_items')) {
            $table = $schema->createTable('mv_inventory_stock_items');
            $table->addColumn('id', 'bigint', [
                'autoincrement' => true,
                'notnull' => true,
                'length' => 8,
            ]);
            $table->addColumn('name', 'string', [
                'notnull' => true,
                'length' => 255,
                'default' => '',
            ]);
            $table->addColumn('provider_urls_json', 'text', [
                'notnull' => false,
                'default' => null,
                'length' => 65535,
            ]);
            $table->addColumn('created_at', 'datetime', [
                'notnull' => true,
                'default' => '1970-01-01 00:00:00',
            ]);
            $table->addColumn('updated_at', 'datetime', [
                'notnull' => true,
                'default' => '1970-01-01 00:00:00',
            ]);
            $table->setPrimaryKey(['id']);
        }

        // ── mv_inventory_stock_variants (FK → stock_items) ───────────
        if (!$schema->hasTable('mv_inventory_stock_variants')) {
            $table = $schema->createTable('mv_inventory_stock_variants');
            $table->addColumn('id', 'bigint', [
                'autoincrement' => true,
                'notnull' => true,
                'length' => 8,
            ]);
            $table->addColumn('stock_item_id', 'bigint', [
                'notnull' => true,
                'length' => 8,
                'default' => 0,
            ]);
            $table->addColumn('label', 'string', [
                'notnull' => true,
                'length' => 100,
                'default' => '',
            ]);
            $table->addColumn('amount', Types::INTEGER, [
                'notnull' => true,
                'default' => 0,
                'unsigned' => true,
            ]);
            $table->addColumn('cost', 'decimal', [
                'notnull' => true,
                'default' => '0.00',
                'precision' => 10,
                'scale' => 2,
            ]);
            $table->addColumn('min_threshold', Types::INTEGER, [
                'notnull' => true,
                'default' => 0,
                'unsigned' => true,
            ]);
            $table->setPrimaryKey(['id']);
            $table->addForeignKeyConstraint(
                $schema->getTable('mv_inventory_stock_items'),
                ['stock_item_id'],
                ['id'],
                ['onDelete' => 'CASCADE']
            );
        }

        // ── mv_inventory_item_categories (FK → general_material, categories) ──
        if (!$schema->hasTable('mv_inventory_item_categories')) {
            $table = $schema->createTable('mv_inventory_item_categories');
            $table->addColumn('item_id', 'bigint', [
                'notnull' => true,
                'length' => 8,
                'default' => 0,
            ]);
            $table->addColumn('category_id', 'bigint', [
                'notnull' => true,
                'length' => 8,
                'default' => 0,
            ]);
            $table->setPrimaryKey(['item_id', 'category_id']);
            $table->addForeignKeyConstraint(
                $schema->getTable('mv_inventory_general_material'),
                ['item_id'],
                ['id'],
                ['onDelete' => 'CASCADE']
            );
            $table->addForeignKeyConstraint(
                $schema->getTable('mv_inventory_categories'),
                ['category_id'],
                ['id'],
                ['onDelete' => 'CASCADE']
            );
        }

        // ── mv_inventory_sales (FK → stock_items, stock_variants) ────
        if (!$schema->hasTable('mv_inventory_sales')) {
            $table = $schema->createTable('mv_inventory_sales');
            $table->addColumn('id', 'bigint', [
                'autoincrement' => true,
                'notnull' => true,
                'length' => 8,
            ]);
            $table->addColumn('stock_item_id', 'bigint', [
                'notnull' => false,
                'length' => 8,
                'default' => null,
            ]);
            $table->addColumn('variant_id', 'bigint', [
                'notnull' => false,
                'length' => 8,
                'default' => null,
            ]);
            $table->addColumn('date', 'date', [
                'notnull' => true,
                'default' => '1970-01-01',
            ]);
            $table->addColumn('quantity', Types::INTEGER, [
                'notnull' => true,
                'default' => 0,
                'unsigned' => true,
            ]);
            $table->addColumn('unit_price', 'decimal', [
                'notnull' => true,
                'default' => '0.00',
                'precision' => 10,
                'scale' => 2,
            ]);
            $table->addColumn('total_price', 'decimal', [
                'notnull' => true,
                'default' => '0.00',
                'precision' => 10,
                'scale' => 2,
            ]);
            $table->addColumn('notes', 'text', [
                'notnull' => false,
                'default' => null,
                'length' => 65535,
            ]);
            $table->addColumn('created_at', 'datetime', [
                'notnull' => true,
                'default' => '1970-01-01 00:00:00',
            ]);
            $table->setPrimaryKey(['id']);
            if ($schema->hasTable('mv_inventory_stock_items')) {
                $stockTable = $schema->getTable('mv_inventory_stock_items');
                $table->addForeignKeyConstraint($stockTable, ['stock_item_id'], ['id'], ['onDelete' => 'SET NULL']);
            }
            if ($schema->hasTable('mv_inventory_stock_variants')) {
                $varTable = $schema->getTable('mv_inventory_stock_variants');
                $table->addForeignKeyConstraint($varTable, ['variant_id'], ['id'], ['onDelete' => 'SET NULL']);
            }
        }

        return $schema;
    }
}
