<?php

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

return new class extends Migration
{
    /**
     * Form factor groups device presets into platform + size families
     * (iphone_portrait, ipad_portrait, android_phone_portrait,
     * android_tablet_portrait). A device's form_factor is what binds a preset
     * to the right per-screen layout variant on the project side — mixing an
     * iPhone composition with an iPad export would stretch screenshots and
     * frames beyond what the responsive engine can rescue.
     */
    public function up(): void
    {
        Schema::table('device_presets', function (Blueprint $table) {
            $table->string('form_factor', 32)->default('iphone_portrait')->after('key')->index();
        });

        foreach ($this->presetFactors() as $row) {
            DB::table('device_presets')
                ->where('platform', $row['platform'])
                ->where('category', $row['category'])
                ->update(['form_factor' => $row['factor'], 'updated_at' => now()]);
        }
    }

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

    /** @return array<int, array{platform: string, category: string, factor: string}> */
    private function presetFactors(): array
    {
        return [
            ['platform' => 'ios', 'category' => 'phone', 'factor' => 'iphone_portrait'],
            ['platform' => 'ios', 'category' => 'tablet', 'factor' => 'ipad_portrait'],
            ['platform' => 'android', 'category' => 'phone', 'factor' => 'android_phone_portrait'],
            ['platform' => 'android', 'category' => 'tablet', 'factor' => 'android_tablet_portrait'],
        ];
    }
};
