<?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 the audit log table (oc_mv_audit_log).
 *
 * Part of Issue #38 — DB migration for audit log table.
 * This table is append-only. Encrypted fields show '[verschlüsselt]'
 * instead of actual values.
 */
class Version000006Date20260407000005 extends SimpleMigrationStep {

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

        if ($schema->hasTable('mv_audit_log')) {
            return null;
        }

        $table = $schema->createTable('mv_audit_log');

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

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

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

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

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

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

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

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

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

        // ── Indexes ──────────────────────────────────────────────────
        $table->addIndex(['entitaet', 'entitaet_id'], 'mv_audit_entity_idx');
        $table->addIndex(['zeitpunkt'], 'mv_audit_zeit_idx');
        $table->addIndex(['nc_user_id'], 'mv_audit_user_idx');

        return $schema;
    }
}
