<?php

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

/**
 * Adds a curated `family_id` to device_presets so the responsive engine can
 * swap a frame layer's device preset when resolving across factor boundaries
 * (iOS ↔ Android, phone ↔ tablet) — not only across orientation flips.
 *
 * Each family groups the equivalent screenshot tier across iPhone / iPad /
 * Android phone / Android tablet, both portraits and landscapes (8 members
 * per family). Presets without a sensible cross-platform analogue (iPhone SE,
 * iPhone 8 Plus, OnePlus 12, Lenovo Tab P12) stay family-less; the resolver
 * keeps the original device preset for those — user can override per-factor.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('device_presets', function (Blueprint $table) {
            $table->string('family_id', 32)->nullable()->after('rotation_pair_id');
            $table->index('family_id');
        });

        $families = [
            'pro_max' => [
                'iphone-16-pro-max',
                'ipad-pro-13',
                'android-pixel-9-pro',
                'android-pixel-tablet',
            ],
            'pro' => [
                'iphone-16-pro',
                'ipad-pro-11',
                'android-galaxy-s24-ultra',
                'android-galaxy-tab-s10',
            ],
            'plus' => [
                'iphone-16-plus',
                'ipad-air-13',
                'android-galaxy-s24',
                'android-galaxy-tab-s9',
            ],
            'standard' => [
                'iphone-16',
                'ipad-pro-12-9',
                'android-pixel-9',
                'android-oneplus-pad-2',
            ],
        ];

        DB::transaction(function () use ($families) {
            foreach ($families as $familyId => $portraitKeys) {
                $allKeys = [];
                foreach ($portraitKeys as $key) {
                    $allKeys[] = $key;
                    $allKeys[] = $key . '-landscape';
                }
                DB::table('device_presets')
                    ->whereIn('key', $allKeys)
                    ->update(['family_id' => $familyId]);
            }
        });
    }

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