<?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 families table (oc_mv_families).
 *
 * Part of Issue #27 — DB migrations for families table.
 * Banking fields (kontoinhaber, IBAN) are stored encrypted at rest
 * via ICrypto. The family_id FK on mv_members was already created
 * in Issue #18.
 */
class Version000003Date20260407000002 extends SimpleMigrationStep {

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

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

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

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

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

        // ── Banking (encrypted at rest) ──────────────────────────────
        $table->addColumn('kontoinhaber_encrypted', Types::TEXT, [
            'notnull' => false,
        ]);

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

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

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

        // ── Timestamps ───────────────────────────────────────────────
        $table->addColumn('created_at', Types::DATETIME, [
            'notnull' => true,
        ]);

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

        // ── Indexes ──────────────────────────────────────────────────
        $table->addIndex(['name'], 'mv_families_name_idx');

        return $schema;
    }
}
