<?php

declare(strict_types=1);

namespace DoctrineMigrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

final class Version20260317100224 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Create homework_rules and homework_rules_history tables';
    }

    public function up(Schema $schema): void
    {
        $this->addSql(<<<'SQL'
            CREATE TABLE homework_rules (
                id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
                tenant_id UUID NOT NULL UNIQUE,
                rules JSONB NOT NULL DEFAULT '[]',
                enforcement_mode VARCHAR(20) DEFAULT 'soft' NOT NULL,
                enabled BOOLEAN DEFAULT true NOT NULL,
                created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
            )
            SQL);

        $this->addSql('CREATE INDEX idx_homework_rules_tenant ON homework_rules(tenant_id)');

        $this->addSql(<<<'SQL'
            CREATE TABLE homework_rules_history (
                id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
                tenant_id UUID NOT NULL,
                previous_rules JSONB,
                new_rules JSONB NOT NULL,
                enforcement_mode VARCHAR(20) NOT NULL,
                enabled BOOLEAN NOT NULL,
                changed_by UUID REFERENCES users(id),
                changed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
            )
            SQL);

        $this->addSql('CREATE INDEX idx_homework_rules_history_tenant ON homework_rules_history(tenant_id)');
        $this->addSql('CREATE INDEX idx_homework_rules_history_changed_at ON homework_rules_history(changed_at DESC)');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('DROP TABLE IF EXISTS homework_rules_history');
        $this->addSql('DROP TABLE IF EXISTS homework_rules');
    }
}
