<?php

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

return new class extends Migration
{
    /**
     * Legacy Apple tiers that Apple's App Store Connect still accepts as
     * scaling fallbacks: 5.5" iPhone (iPhone 6 Plus / 7 Plus / 8 Plus pixels)
     * and 12.9" iPad Pro. Covering them unlocks submissions for apps that
     * haven't migrated to the 6.9"/6.3" and ipad-13/11 tiers only.
     */
    public function up(): void
    {
        $hasFactor = Schema::hasColumn('device_presets', 'form_factor');
        $now = now();

        $rows = [
            [
                'key' => 'iphone-8-plus',
                'label' => 'iPhone 8 Plus (5.5")',
                'platform' => 'ios',
                'category' => 'phone',
                'apple_tier' => 'iphone-5.5',
                'export_w' => 1242,
                'export_h' => 2208,
                'frame_svg_path' => null,
                'safe_area' => json_encode(['top' => 40, 'right' => 0, 'bottom' => 0, 'left' => 0]),
                'is_active' => true,
                'created_at' => $now,
                'updated_at' => $now,
            ],
            [
                'key' => 'ipad-pro-12-9',
                'label' => 'iPad Pro 12.9" (legacy)',
                'platform' => 'ios',
                'category' => 'tablet',
                'apple_tier' => 'ipad-12.9',
                'export_w' => 2048,
                'export_h' => 2732,
                'frame_svg_path' => null,
                'safe_area' => json_encode(['top' => 48, 'right' => 0, 'bottom' => 32, 'left' => 0]),
                'is_active' => true,
                'created_at' => $now,
                'updated_at' => $now,
            ],
        ];

        if ($hasFactor) {
            foreach ($rows as &$row) {
                $row['form_factor'] = $row['category'] === 'tablet' ? 'ipad_portrait' : 'iphone_portrait';
            }
            unset($row);
        }

        $updateCols = ['label', 'platform', 'category', 'apple_tier', 'export_w', 'export_h', 'safe_area', 'is_active', 'updated_at'];
        if ($hasFactor) {
            $updateCols[] = 'form_factor';
        }

        DB::table('device_presets')->upsert($rows, ['key'], $updateCols);
    }

    public function down(): void
    {
        DB::table('device_presets')
            ->whereIn('key', ['iphone-8-plus', 'ipad-pro-12-9'])
            ->delete();
    }
};
