<?php

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

/**
 * Seeds the iPhone 17 series (announced September 2025) — iPhone 17, 17 Plus,
 * 17 Pro, 17 Pro Max — both portrait + landscape variants. Display tiers
 * match the iPhone 16 generation (17 Pro Max + 17 Plus on the 6.9" tier, 17
 * Pro + 17 on the 6.3" tier) so the App Store Connect canvas dimensions and
 * safe-area insets carry over from the iPhone 16 seed.
 *
 * Family-id reassignment: iPhone 17 series TAKES OVER the iPhone slots in the
 * curated cross-platform family map (`pro_max` / `pro` / `plus` / `standard`).
 * The iPhone 16 rows remain in the table for users who specifically need
 * them, but their `family_id` flips to null — they no longer participate in
 * cross-factor frame swaps via `LayoutResolver::applyReflowIntents`. iPhone
 * 17 Pro Max is the new canonical Apple flagship for resolver lookups.
 *
 * The rotation_pair_id seed migration (2026_04_27_000002) walks every row by
 * `<base>` / `<base>-landscape` suffix matching, so this migration's new rows
 * are paired automatically the next time it runs. We also inline-pair them
 * here so the database is consistent immediately without depending on a
 * follow-up data migration.
 *
 * The real-frame backfill (2026_05_20_120002) reads the manifest at run
 * time — since the manifest is being repointed at iphone-17-pro-max in the
 * same release, the backfill will flag iPhone 17 Pro Max as the
 * `has_real_frame=true` row. iPhone 16 Pro Max's existing flag (set by the
 * backfill earlier in this release) will be cleared as part of that
 * repoint — done in this migration's `up()` for atomicity.
 */
return new class extends Migration
{
    public function up(): void
    {
        $now = now();

        $portraits = [
            [
                'key' => 'iphone-17-pro-max',
                'label' => 'iPhone 17 Pro Max (6.9")',
                'category' => 'phone',
                'apple_tier' => 'iphone-6.9',
                'export_w' => 1320,
                'export_h' => 2868,
                'safe_area' => ['top' => 96, 'right' => 0, 'bottom' => 64, 'left' => 0],
                'family_id' => 'pro_max',
            ],
            [
                'key' => 'iphone-17-pro',
                'label' => 'iPhone 17 Pro (6.3")',
                'category' => 'phone',
                'apple_tier' => 'iphone-6.3',
                'export_w' => 1206,
                'export_h' => 2622,
                'safe_area' => ['top' => 88, 'right' => 0, 'bottom' => 60, 'left' => 0],
                'family_id' => 'pro',
            ],
            [
                'key' => 'iphone-17-plus',
                'label' => 'iPhone 17 Plus (6.9")',
                'category' => 'phone',
                'apple_tier' => 'iphone-6.9',
                'export_w' => 1320,
                'export_h' => 2868,
                'safe_area' => ['top' => 96, 'right' => 0, 'bottom' => 64, 'left' => 0],
                'family_id' => 'plus',
            ],
            [
                'key' => 'iphone-17',
                'label' => 'iPhone 17 (6.3")',
                'category' => 'phone',
                'apple_tier' => 'iphone-6.3',
                'export_w' => 1206,
                'export_h' => 2622,
                'safe_area' => ['top' => 88, 'right' => 0, 'bottom' => 60, 'left' => 0],
                'family_id' => 'standard',
            ],
        ];

        DB::transaction(function () use ($portraits, $now) {
            // Insert portrait rows.
            foreach ($portraits as $p) {
                DB::table('device_presets')->updateOrInsert(
                    ['key' => $p['key']],
                    [
                        'label' => $p['label'],
                        'platform' => 'ios',
                        'category' => $p['category'],
                        'form_factor' => 'iphone_portrait',
                        'apple_tier' => $p['apple_tier'],
                        'export_w' => $p['export_w'],
                        'export_h' => $p['export_h'],
                        'frame_svg_path' => null,
                        'safe_area' => json_encode($p['safe_area']),
                        'family_id' => $p['family_id'],
                        'is_active' => true,
                        'created_at' => $now,
                        'updated_at' => $now,
                    ],
                );
            }

            // Insert landscape twins. Width and height swap; safe-area rotates 90° CCW.
            foreach ($portraits as $p) {
                $landscapeKey = $p['key'].'-landscape';
                $sa = $p['safe_area'];
                DB::table('device_presets')->updateOrInsert(
                    ['key' => $landscapeKey],
                    [
                        'label' => $p['label'].' (Landscape)',
                        'platform' => 'ios',
                        'category' => $p['category'],
                        'form_factor' => 'iphone_landscape',
                        'apple_tier' => $p['apple_tier'],
                        'export_w' => $p['export_h'],
                        'export_h' => $p['export_w'],
                        'frame_svg_path' => null,
                        // Rotate safe-area 90° CCW: top→left, right→top, bottom→right, left→bottom.
                        'safe_area' => json_encode([
                            'top' => $sa['left'],
                            'right' => $sa['top'],
                            'bottom' => $sa['right'],
                            'left' => $sa['bottom'],
                        ]),
                        'family_id' => $p['family_id'],
                        'is_active' => true,
                        'created_at' => $now,
                        'updated_at' => $now,
                    ],
                );
            }

            // Rotation pairs: link each portrait to its landscape twin in both directions.
            foreach ($portraits as $p) {
                $portraitId = DB::table('device_presets')->where('key', $p['key'])->value('id');
                $landscapeId = DB::table('device_presets')->where('key', $p['key'].'-landscape')->value('id');
                if ($portraitId && $landscapeId) {
                    DB::table('device_presets')->where('id', $portraitId)->update([
                        'rotation_pair_id' => $landscapeId,
                        'updated_at' => $now,
                    ]);
                    DB::table('device_presets')->where('id', $landscapeId)->update([
                        'rotation_pair_id' => $portraitId,
                        'updated_at' => $now,
                    ]);
                }
            }

            // Reassign family ownership: iPhone 17 series takes over the iPhone
            // slots in the cross-platform family map. iPhone 16 series rows
            // (and their landscape twins) clear `family_id` so they don't
            // collide with iPhone 17 during resolver lookups.
            $iphone16Keys = [
                'iphone-16-pro-max', 'iphone-16-pro-max-landscape',
                'iphone-16-pro', 'iphone-16-pro-landscape',
                'iphone-16-plus', 'iphone-16-plus-landscape',
                'iphone-16', 'iphone-16-landscape',
            ];
            DB::table('device_presets')
                ->whereIn('key', $iphone16Keys)
                ->update(['family_id' => null, 'updated_at' => $now]);

            // Clear the real-frame flag on iPhone 16 Pro Max — the manifest is
            // being repointed at iPhone 17 Pro Max in the same release. If a
            // future release adds iPhone 16 frame assets back into the
            // manifest, the next backfill will re-flag it cleanly.
            DB::table('device_presets')
                ->whereIn('key', ['iphone-16-pro-max', 'iphone-16-pro-max-landscape'])
                ->update([
                    'has_real_frame' => false,
                    'real_frame_color_options' => null,
                    'real_frame_screen_rect' => null,
                    'updated_at' => $now,
                ]);

            // Apply the real-frame backfill inline for the newly-seeded iPhone
            // 17 series. The standalone backfill migration (120002) already
            // ran during this release window with the previous manifest
            // contents (iPhone 16 Pro Max), so it won't re-fire here.
            // Re-reading the manifest now picks up the post-repoint entry
            // and flags both the portrait + landscape rows of every device.
            $manifestPath = public_path('device-frames/manifest.json');
            if (is_file($manifestPath)) {
                $raw = @file_get_contents($manifestPath);
                $manifest = $raw !== false ? json_decode($raw, true) : null;
                if (is_array($manifest) && isset($manifest['frames']) && is_array($manifest['frames'])) {
                    foreach ($manifest['frames'] as $frame) {
                        if (! is_array($frame) || empty($frame['device_preset_id'])) {
                            continue;
                        }
                        $key = $frame['device_preset_id'];
                        // Only re-apply for iPhone 17 rows the seed just
                        // inserted — other devices (iPad, Pixel) were already
                        // backfilled by 120002 and shouldn't be touched.
                        if (! str_starts_with($key, 'iphone-17')) {
                            continue;
                        }
                        DB::table('device_presets')
                            ->whereIn('key', [$key, $key.'-landscape'])
                            ->update([
                                'has_real_frame' => true,
                                'real_frame_color_options' => isset($frame['colors']) ? json_encode($frame['colors']) : null,
                                'real_frame_screen_rect' => isset($frame['screen_rect']) ? json_encode($frame['screen_rect']) : null,
                                'updated_at' => $now,
                            ]);
                    }
                }
            }
        });
    }

    public function down(): void
    {
        $iphone17Keys = [
            'iphone-17-pro-max', 'iphone-17-pro-max-landscape',
            'iphone-17-pro', 'iphone-17-pro-landscape',
            'iphone-17-plus', 'iphone-17-plus-landscape',
            'iphone-17', 'iphone-17-landscape',
        ];

        DB::transaction(function () use ($iphone17Keys) {
            // Restore family_id on iPhone 16 series before dropping iPhone 17 —
            // otherwise the family map would have null iPhone slots after
            // down().
            DB::table('device_presets')
                ->where('key', 'iphone-16-pro-max')
                ->update(['family_id' => 'pro_max']);
            DB::table('device_presets')
                ->where('key', 'iphone-16-pro-max-landscape')
                ->update(['family_id' => 'pro_max']);
            DB::table('device_presets')
                ->where('key', 'iphone-16-pro')
                ->update(['family_id' => 'pro']);
            DB::table('device_presets')
                ->where('key', 'iphone-16-pro-landscape')
                ->update(['family_id' => 'pro']);
            DB::table('device_presets')
                ->where('key', 'iphone-16-plus')
                ->update(['family_id' => 'plus']);
            DB::table('device_presets')
                ->where('key', 'iphone-16-plus-landscape')
                ->update(['family_id' => 'plus']);
            DB::table('device_presets')
                ->where('key', 'iphone-16')
                ->update(['family_id' => 'standard']);
            DB::table('device_presets')
                ->where('key', 'iphone-16-landscape')
                ->update(['family_id' => 'standard']);

            DB::table('device_presets')
                ->whereIn('key', $iphone17Keys)
                ->delete();
        });
    }
};
