<?php

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

/**
 * Re-add `device_presets.family_id` for cross-factor device propagation.
 *
 * Originally introduced for responsive-engine v3 (frame swap on cross-
 * orientation derive), then dropped by `2026_05_21_150000_rip_multi_factor`
 * when v3 was retired. The multi-device pivot's Phase 3.5 (see
 * `multi-device-plan.md`) brings it back for a different purpose:
 * one-shot stamp lookup when a frame layer is stamped into a new factor.
 *
 * Difference from v3 use: this is USER-TRIGGERED + VISIBLE, never a
 * silent render-time swap. Phase 3.5 only consumes `family_id` during
 * stamp operations (project create with multi-factor / add-factor mid-
 * project). Live edit-time propagation (swap-device on iPhone also
 * updates iPad) is deferred.
 *
 * Canonical 'pro_max' family — 8 rows total (4 portrait + 4 landscape):
 *   iphone-17-pro-max               (iphone_portrait)
 *   iphone-17-pro-max-landscape     (iphone_landscape)
 *   ipad-pro-13                     (ipad_portrait)
 *   ipad-pro-13-landscape           (ipad_landscape)
 *   android-galaxy-s26              (android_phone_portrait)
 *   android-galaxy-s26-landscape    (android_phone_landscape)
 *   android-galaxy-tab-s8-ultra            (android_10_tablet_portrait)
 *   android-galaxy-tab-s8-ultra-landscape  (android_10_tablet_landscape)
 *
 * Other devices stay family-less for now — they participate as explicit
 * per-factor picks. Additional families (pro, plus, standard, etc.) get
 * seeded as the device catalog expands.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('device_presets', function (Blueprint $table) {
            if (! Schema::hasColumn('device_presets', 'family_id')) {
                $table->string('family_id', 32)->nullable()->after('form_factor');
                $table->index('family_id');
            }
        });

        $proMaxKeys = [
            'iphone-17-pro-max',
            'iphone-17-pro-max-landscape',
            'ipad-pro-13',
            'ipad-pro-13-landscape',
            'android-galaxy-s26',
            'android-galaxy-s26-landscape',
            'android-galaxy-tab-s8-ultra',
            'android-galaxy-tab-s8-ultra-landscape',
        ];

        DB::table('device_presets')
            ->whereIn('key', $proMaxKeys)
            ->update([
                'family_id' => 'pro_max',
                'updated_at' => now(),
            ]);
    }

    public function down(): void
    {
        Schema::table('device_presets', function (Blueprint $table) {
            if (Schema::hasColumn('device_presets', 'family_id')) {
                $table->dropIndex(['family_id']);
                $table->dropColumn('family_id');
            }
        });
    }
};
