<?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 sync queue and calendar events tables.
 *
 * Shared queue for CalendarSync and ContactsSync background processing.
 * Calendar events table for storing VCalendar data until CalDAV push.
 *
 * Part of Issues #50, #51.
 */
class Version000011Date20260407000010 extends SimpleMigrationStep {

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

        // ── Sync queue (shared by Calendar + Contacts sync) ─────────
        if (!$schema->hasTable('mv_sync_queue')) {
            $table = $schema->createTable('mv_sync_queue');

            $table->addColumn('id', Types::BIGINT, [
                'autoincrement' => true,
                'notnull' => true,
                'unsigned' => true,
            ]);
            $table->addColumn('entity_type', Types::STRING, [
                'notnull' => true,
                'length' => 50,
            ]);
            $table->addColumn('entity_id', Types::BIGINT, [
                'notnull' => true,
                'unsigned' => true,
            ]);
            $table->addColumn('created_at', Types::DATETIME, [
                'notnull' => true,
            ]);

            $table->setPrimaryKey(['id']);
            $table->addIndex(['entity_type'], 'mv_sync_queue_type_idx');

            $schemaChanged = true;
        }

        // ── Calendar events staging table ────────────────────────────
        if (!$schema->hasTable('mv_calendar_events')) {
            $table = $schema->createTable('mv_calendar_events');

            $table->addColumn('id', Types::BIGINT, [
                'autoincrement' => true,
                'notnull' => true,
                'unsigned' => true,
            ]);
            $table->addColumn('event_uri', Types::STRING, [
                'notnull' => true,
                'length' => 255,
            ]);
            $table->addColumn('vcalendar_data', Types::TEXT, [
                'notnull' => true,
            ]);
            $table->addColumn('calendar_uri', Types::STRING, [
                'notnull' => true,
                'length' => 255,
            ]);
            $table->addColumn('created_at', Types::DATETIME, [
                'notnull' => true,
            ]);
            $table->addColumn('updated_at', Types::DATETIME, [
                'notnull' => true,
            ]);

            $table->setPrimaryKey(['id']);
            $table->addUniqueIndex(['event_uri'], 'mv_cal_event_uri_uniq');
            $table->addIndex(['calendar_uri'], 'mv_cal_calendar_idx');

            $schemaChanged = true;
        }

        return $schemaChanged ? $schema : null;
    }
}
