<?php

declare(strict_types=1);

namespace DoctrineMigrations;

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

final class Version20260327211549 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Création des tables grades et grade_events pour la saisie de notes et l\'audit';
    }

    public function up(Schema $schema): void
    {
        $this->addSql(<<<'SQL'
            CREATE TABLE grades (
                id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
                tenant_id UUID NOT NULL,
                evaluation_id UUID NOT NULL REFERENCES evaluations(id),
                student_id UUID NOT NULL REFERENCES users(id),
                value DECIMAL(5,2),
                status VARCHAR(20) NOT NULL DEFAULT 'graded',
                created_by UUID NOT NULL REFERENCES users(id),
                created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                UNIQUE (evaluation_id, student_id)
            )
            SQL);

        $this->addSql(<<<'SQL'
            CREATE INDEX idx_grades_tenant ON grades(tenant_id)
            SQL);

        $this->addSql(<<<'SQL'
            CREATE INDEX idx_grades_evaluation ON grades(evaluation_id)
            SQL);

        $this->addSql(<<<'SQL'
            CREATE INDEX idx_grades_student ON grades(student_id)
            SQL);

        $this->addSql(<<<'SQL'
            CREATE TABLE grade_events (
                id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
                grade_id UUID NOT NULL REFERENCES grades(id),
                event_type VARCHAR(50) NOT NULL,
                old_value DECIMAL(5,2),
                new_value DECIMAL(5,2),
                old_status VARCHAR(20),
                new_status VARCHAR(20),
                created_by UUID NOT NULL REFERENCES users(id),
                created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
            )
            SQL);

        $this->addSql(<<<'SQL'
            CREATE INDEX idx_grade_events_grade ON grade_events(grade_id)
            SQL);
    }

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