<?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 injury tracking tables (injuries, injury_involved).
 *
 * Part of Issue #56.
 */
class Version000010Date20260407000009 extends SimpleMigrationStep {

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

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

            $table->addColumn('id', Types::BIGINT, [
                'autoincrement' => true,
                'notnull' => true,
                'unsigned' => true,
            ]);
            $table->addColumn('datum', Types::DATE, [
                'notnull' => true,
            ]);
            $table->addColumn('member_id', Types::BIGINT, [
                'notnull' => true,
                'unsigned' => true,
            ]);
            $table->addColumn('lager_id', Types::BIGINT, [
                'notnull' => false,
                'unsigned' => true,
            ]);
            $table->addColumn('activity_name', Types::STRING, [
                'notnull' => false,
                'length' => 255,
            ]);
            $table->addColumn('beschreibung', Types::TEXT, [
                'notnull' => true,
            ]);
            $table->addColumn('created_by', Types::STRING, [
                'notnull' => true,
                'length' => 64,
            ]);
            $table->addColumn('created_at', Types::DATETIME, [
                'notnull' => true,
            ]);

            $table->setPrimaryKey(['id']);
            $table->addIndex(['member_id'], 'mv_injuries_member_idx');
            $table->addIndex(['lager_id'], 'mv_injuries_lager_idx');
            $table->addIndex(['datum'], 'mv_injuries_datum_idx');

            $schemaChanged = true;
        }

        // ── Injury-Involved m:n table ───────────────────────────────
        if (!$schema->hasTable('mv_injury_involved')) {
            $table = $schema->createTable('mv_injury_involved');

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

            $table->setPrimaryKey(['injury_id', 'member_id']);
            $table->addIndex(['member_id'], 'mv_injury_inv_member_idx');

            $schemaChanged = true;
        }

        return $schemaChanged ? $schema : null;
    }
}
