<?php

declare(strict_types=1);

namespace DoctrineMigrations;

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

final class Version20260221093719 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Create class_assignments table and extend users for student enrollment';
    }

    public function up(Schema $schema): void
    {
        $this->addSql(<<<'SQL'
            CREATE TABLE class_assignments (
                id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
                tenant_id UUID NOT NULL,
                user_id UUID NOT NULL,
                school_class_id UUID NOT NULL,
                academic_year_id UUID NOT NULL,
                assigned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                UNIQUE(user_id, academic_year_id),
                CONSTRAINT fk_class_assignments_user FOREIGN KEY (user_id) REFERENCES users(id),
                CONSTRAINT fk_class_assignments_class FOREIGN KEY (school_class_id) REFERENCES school_classes(id)
            )
        SQL);

        $this->addSql('CREATE INDEX idx_class_assignments_class ON class_assignments(school_class_id)');
        $this->addSql('CREATE INDEX idx_class_assignments_tenant ON class_assignments(tenant_id)');

        $this->addSql('ALTER TABLE users ALTER COLUMN email DROP NOT NULL');
        $this->addSql('ALTER TABLE users ADD COLUMN student_number VARCHAR(11)');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('DROP TABLE class_assignments');
        $this->addSql('ALTER TABLE users DROP COLUMN student_number');
        $this->addSql("UPDATE users SET email = 'removed-' || id || '@placeholder.local' WHERE email IS NULL");
        $this->addSql('ALTER TABLE users ALTER COLUMN email SET NOT NULL');
    }
}
