<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Migration;

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

/**
 * Migration: Create Stufen and Stufe history tables, seed default data.
 *
 * Part of Issue #30 — DB migrations for Stufen tables.
 */
class Version000004Date20260407000003 extends SimpleMigrationStep {

    private IDBConnection $db;

    public function __construct(IDBConnection $db) {
        $this->db = $db;
    }

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

        // ── Stufen table ─────────────────────────────────────────────
        if (!$schema->hasTable('mv_stufen')) {
            $table = $schema->createTable('mv_stufen');

            $table->addColumn('id', Types::BIGINT, [
                'autoincrement' => true,
                'notnull' => true,
                'unsigned' => true,
            ]);
            $table->setPrimaryKey(['id']);

            $table->addColumn('name', Types::STRING, [
                'notnull' => true,
                'length' => 100,
            ]);

            $table->addColumn('sort_order', Types::INTEGER, [
                'notnull' => true,
                'default' => 0,
            ]);

            $table->addColumn('age_range_min', Types::INTEGER, [
                'notnull' => false,
            ]);

            $table->addColumn('age_range_max', Types::INTEGER, [
                'notnull' => false,
            ]);

            $table->addColumn('color', Types::STRING, [
                'notnull' => false,
                'length' => 7,
            ]);

            $table->addIndex(['sort_order'], 'mv_stufen_sort_idx');

            $schemaChanged = true;
        }

        // ── Stufe history table ──────────────────────────────────────
        if (!$schema->hasTable('mv_stufe_history')) {
            $table = $schema->createTable('mv_stufe_history');

            $table->addColumn('id', Types::BIGINT, [
                'autoincrement' => true,
                'notnull' => true,
                'unsigned' => true,
            ]);
            $table->setPrimaryKey(['id']);

            $table->addColumn('member_id', Types::BIGINT, [
                'notnull' => true,
                'unsigned' => true,
            ]);

            $table->addColumn('stufe_id', Types::BIGINT, [
                'notnull' => true,
                'unsigned' => true,
            ]);

            $table->addColumn('changed_at', Types::DATETIME, [
                'notnull' => true,
            ]);

            $table->addColumn('changed_by', Types::STRING, [
                'notnull' => true,
                'length' => 64,
            ]);

            $table->addIndex(['member_id'], 'mv_stufe_hist_member_idx');
            $table->addIndex(['stufe_id'], 'mv_stufe_hist_stufe_idx');

            $schemaChanged = true;
        }

        return $schemaChanged ? $schema : null;
    }

    /**
     * Seed default Stufen data after schema creation.
     */
    public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
        // Check if default data already exists
        $qb = $this->db->getQueryBuilder();
        $qb->select($qb->createFunction('COUNT(*)'))
            ->from('mv_stufen');
        $result = $qb->executeQuery();
        $count = (int)$result->fetchOne();
        $result->closeCursor();

        if ($count > 0) {
            return;
        }

        $defaults = [
            ['name' => 'Wölflinge', 'sort_order' => 1, 'age_range_min' => 7, 'age_range_max' => 10, 'color' => '#e8fd09'],
            ['name' => 'Pfadfinder', 'sort_order' => 2, 'age_range_min' => 11, 'age_range_max' => 15, 'color' => '#0c800c'],
            ['name' => 'Rover',      'sort_order' => 3, 'age_range_min' => 16, 'age_range_max' => 25, 'color' => '#dd1212'],
        ];

        foreach ($defaults as $stufe) {
            $qb = $this->db->getQueryBuilder();
            $qb->insert('mv_stufen')
                ->values([
                    'name' => $qb->createNamedParameter($stufe['name']),
                    'sort_order' => $qb->createNamedParameter($stufe['sort_order']),
                    'age_range_min' => $qb->createNamedParameter($stufe['age_range_min']),
                    'age_range_max' => $qb->createNamedParameter($stufe['age_range_max']),
                    'color' => $qb->createNamedParameter($stufe['color']),
                ]);
            $qb->executeStatement();
        }

        $output->info('Seeded default Stufen: Woelflinge, Pfadfinder, Rover');
    }
}
