<?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 permissions table (oc_mv_permissions).
 *
 * Part of Issue #35 — DB migration for permissions table.
 * One row per Nextcloud user who has been granted access.
 * Users without a row default to 'none' (no access).
 */
class Version000005Date20260407000004 extends SimpleMigrationStep {

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

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

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

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

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

        $table->addColumn('level', Types::STRING, [
            'notnull' => true,
            'length' => 10,
            'default' => 'none',
        ]);

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

        $table->addColumn('can_see_banking', Types::BOOLEAN, [
            'notnull' => true,
            'default' => false,
        ]);

        $table->addUniqueIndex(['nc_user_id'], 'mv_permissions_user_idx');

        return $schema;
    }
}
