<?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 saved queries table for visual query builder.
 *
 * Part of Issue #53.
 */
class Version000013Date20260407000012 extends SimpleMigrationStep {

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

        if (!$schema->hasTable('mv_saved_queries')) {
            $table = $schema->createTable('mv_saved_queries');

            $table->addColumn('id', Types::BIGINT, [
                'autoincrement' => true,
                'notnull' => true,
                'unsigned' => true,
            ]);
            $table->addColumn('name', Types::STRING, [
                'notnull' => true,
                'length' => 255,
            ]);
            $table->addColumn('query_json', Types::TEXT, [
                'notnull' => true,
            ]);
            $table->addColumn('sort_json', Types::TEXT, [
                'notnull' => false,
            ]);
            $table->addColumn('created_by', Types::STRING, [
                'notnull' => true,
                'length' => 64,
            ]);
            $table->addColumn('created_at', Types::DATETIME, [
                'notnull' => true,
            ]);

            $table->setPrimaryKey(['id']);
            $table->addIndex(['created_by'], 'mv_sq_created_by_idx');

            $schemaChanged = true;
        }

        return $schemaChanged ? $schema : null;
    }
}
