<?php

declare(strict_types=1);

namespace DoctrineMigrations;

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

final class Version20260403084805 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Add machineContextOnly to custom_fields + link FKs on custom_field_values';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE custom_fields ADD COLUMN IF NOT EXISTS machinecontextonly BOOLEAN DEFAULT false NOT NULL');

        $this->addSql('ALTER TABLE custom_field_values ADD COLUMN IF NOT EXISTS machinecomponentlinkid VARCHAR(36) DEFAULT NULL');
        $this->addSql('ALTER TABLE custom_field_values ADD COLUMN IF NOT EXISTS machinepiecelinkid VARCHAR(36) DEFAULT NULL');

        $this->addSql(<<<'SQL'
            DO $$ BEGIN
                IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_cfv_machine_component_link') THEN
                    ALTER TABLE custom_field_values ADD CONSTRAINT fk_cfv_machine_component_link
                        FOREIGN KEY (machinecomponentlinkid) REFERENCES machine_component_links(id) ON DELETE CASCADE;
                END IF;
            END $$;
            SQL);

        $this->addSql(<<<'SQL'
            DO $$ BEGIN
                IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_cfv_machine_piece_link') THEN
                    ALTER TABLE custom_field_values ADD CONSTRAINT fk_cfv_machine_piece_link
                        FOREIGN KEY (machinepiecelinkid) REFERENCES machine_piece_links(id) ON DELETE CASCADE;
                END IF;
            END $$;
            SQL);

        $this->addSql('CREATE INDEX IF NOT EXISTS idx_cfv_machine_component_link ON custom_field_values(machinecomponentlinkid)');
        $this->addSql('CREATE INDEX IF NOT EXISTS idx_cfv_machine_piece_link ON custom_field_values(machinepiecelinkid)');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE custom_field_values DROP CONSTRAINT IF EXISTS fk_cfv_machine_component_link');
        $this->addSql('ALTER TABLE custom_field_values DROP CONSTRAINT IF EXISTS fk_cfv_machine_piece_link');
        $this->addSql('DROP INDEX IF EXISTS idx_cfv_machine_component_link');
        $this->addSql('DROP INDEX IF EXISTS idx_cfv_machine_piece_link');
        $this->addSql('ALTER TABLE custom_field_values DROP COLUMN IF EXISTS machinecomponentlinkid');
        $this->addSql('ALTER TABLE custom_field_values DROP COLUMN IF EXISTS machinepiecelinkid');
        $this->addSql('ALTER TABLE custom_fields DROP COLUMN IF EXISTS machinecontextonly');
    }
}
