<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * Phase 1 of the multi-device pivot (`multi-device-plan.md`): re-introduce
 * `projects.active_form_factors` as a JSON array sibling of the existing
 * single-valued `form_factor` column. Existing rows backfill to
 * `[form_factor]` so every project keeps rendering at the same canvas.
 *
 * Schema-only change — no runtime callsite yet consumes the new column.
 * Phase 2 wires reads + flips the editor; Phase 3 wires writes. Until
 * then `form_factor` remains the single source of truth.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('projects', function (Blueprint $table) {
            $table->json('active_form_factors')->nullable()->after('form_factor');
        });

        // Backfill existing rows so any future read returns a value. Phase 2
        // wires ProjectController::store to set the column on every insert
        // and tightens the constraint to NOT NULL; until then the column
        // stays nullable so test fixtures and any non-Phase-2 callers that
        // create projects don't trip on a missing value.
        DB::statement(
            'UPDATE projects SET active_form_factors = JSON_ARRAY(form_factor) WHERE active_form_factors IS NULL'
        );
    }

    public function down(): void
    {
        Schema::table('projects', function (Blueprint $table) {
            $table->dropColumn('active_form_factors');
        });
    }
};
