<?php

use App\Database\Migration;

/**
 * Phase 2.2 – Galerie x Media Manager Integration
 *
 * Extends iw_gallery_images with optional media_id FK reference.
 * Allows gallery images to reference existing Media Manager assets
 * instead of storing duplicate files. Maintains backward compatibility:
 * – file_path remains a non-null column (existing images)
 * – media_id is NULL for legacy/duplicated images
 * – media_id is NOT NULL for new references to Media Manager
 *
 * This separation allows gradual migration and coexistence of both models.
 */
class ExtendGalleryWithMediaReference extends Migration
{
    public function up(): void
    {
        // Add optional media_id reference (initially NULL for all existing rows)
        $this->db->query("
            ALTER TABLE iw_gallery_images
            ADD COLUMN media_id INT DEFAULT NULL AFTER album_id,
            ADD INDEX idx_media (media_id),
            ADD CONSTRAINT fk_gallery_images_media
                FOREIGN KEY (media_id)
                REFERENCES iw_media(id)
                ON DELETE SET NULL
        ");
    }

    public function down(): void
    {
        // Remove foreign key and column
        $this->db->query("
            ALTER TABLE iw_gallery_images
            DROP CONSTRAINT fk_gallery_images_media
        ");

        $this->db->query("
            ALTER TABLE iw_gallery_images
            DROP INDEX idx_media
        ");

        $this->db->query("
            ALTER TABLE iw_gallery_images
            DROP COLUMN media_id
        ");
    }
}
