<?php

declare(strict_types=1);

namespace DoctrineMigrations;

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

final class Version20260312171810 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Create piece_products join table and migrate data from Piece.productIds JSON column';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('CREATE TABLE IF NOT EXISTS piece_products (piece_id VARCHAR(36) NOT NULL, product_id VARCHAR(36) NOT NULL, PRIMARY KEY (piece_id, product_id))');
        $this->addSql('CREATE INDEX IF NOT EXISTS IDX_87C835B5C40FCFA8 ON piece_products (piece_id)');
        $this->addSql('CREATE INDEX IF NOT EXISTS IDX_87C835B54584665A ON piece_products (product_id)');
        $this->addSql('ALTER TABLE piece_products DROP CONSTRAINT IF EXISTS FK_87C835B5C40FCFA8');
        $this->addSql('ALTER TABLE piece_products ADD CONSTRAINT FK_87C835B5C40FCFA8 FOREIGN KEY (piece_id) REFERENCES pieces (id) ON DELETE CASCADE NOT DEFERRABLE');
        $this->addSql('ALTER TABLE piece_products DROP CONSTRAINT IF EXISTS FK_87C835B54584665A');
        $this->addSql('ALTER TABLE piece_products ADD CONSTRAINT FK_87C835B54584665A FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE NOT DEFERRABLE');

        // Migrate Piece.productIds JSON array → piece_products join table
        $this->addSql(<<<'SQL'
            INSERT INTO piece_products (piece_id, product_id)
            SELECT DISTINCT p.id, pid.value
            FROM pieces p,
            LATERAL jsonb_array_elements_text(p.productids::jsonb) AS pid(value)
            WHERE p.productids IS NOT NULL
              AND p.productids::jsonb != '[]'::jsonb
              AND jsonb_array_length(p.productids::jsonb) > 0
              AND EXISTS (SELECT 1 FROM products pr WHERE pr.id = pid.value)
              AND NOT EXISTS (SELECT 1 FROM piece_products pp WHERE pp.piece_id = p.id AND pp.product_id = pid.value)
            SQL);
    }

    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE piece_products DROP CONSTRAINT IF EXISTS FK_87C835B5C40FCFA8');
        $this->addSql('ALTER TABLE piece_products DROP CONSTRAINT IF EXISTS FK_87C835B54584665A');
        $this->addSql('DROP TABLE IF EXISTS piece_products');
    }
}
