<?php

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

/**
 * Seeds the Pixel 10 series (announced August 2025) — Pixel 10 + Pixel 10 Pro —
 * both portrait + landscape variants. Screenshot dimensions on the Play Store
 * are range-based (1080–7680 px per `android-screenshot-specs.md`) so we
 * mirror Pixel 9 dims as a baseline (1080×2424 for Pixel 10, 1280×2856 for
 * Pixel 10 Pro); fine-tune if Google publishes generation-specific specs.
 *
 * Family-id reassignment: Pixel 10 series TAKES OVER the Android-phone slots
 * in the curated cross-platform family map. Pixel 9 series rows stay seeded
 * (users can still pick them explicitly) but their `family_id` flips to
 * null — they no longer participate in cross-factor frame swaps via
 * `LayoutResolver::applyReflowIntents`.
 *
 * Real-frame backfill: the standalone backfill migration (120002) already ran
 * during this release window with the previous manifest contents (Pixel 9
 * Pro). This migration clears Pixel 9 Pro's `has_real_frame` flag and
 * re-reads the manifest inline to apply the flag to Pixel 10 Pro.
 */
return new class extends Migration
{
    public function up(): void
    {
        $now = now();

        $portraits = [
            [
                'key' => 'android-pixel-10-pro',
                'label' => 'Pixel 10 Pro',
                'export_w' => 1280,
                'export_h' => 2856,
                'family_id' => 'pro_max',
            ],
            [
                'key' => 'android-pixel-10',
                'label' => 'Pixel 10',
                'export_w' => 1080,
                'export_h' => 2424,
                'family_id' => 'standard',
            ],
        ];

        DB::transaction(function () use ($portraits, $now) {
            foreach ($portraits as $p) {
                // Portrait row.
                DB::table('device_presets')->updateOrInsert(
                    ['key' => $p['key']],
                    [
                        'label' => $p['label'],
                        'platform' => 'android',
                        'category' => 'phone',
                        'form_factor' => 'android_phone_portrait',
                        'apple_tier' => null,
                        'export_w' => $p['export_w'],
                        'export_h' => $p['export_h'],
                        'frame_svg_path' => null,
                        // Pixel safe-area: status bar 80px top, nav 48px bottom — same
                        // proportions as Pixel 9.
                        'safe_area' => json_encode([
                            'top' => 80, 'right' => 0, 'bottom' => 48, 'left' => 0,
                        ]),
                        'family_id' => $p['family_id'],
                        'is_active' => true,
                        'created_at' => $now,
                        'updated_at' => $now,
                    ],
                );

                // Landscape twin.
                $landscapeKey = $p['key'].'-landscape';
                DB::table('device_presets')->updateOrInsert(
                    ['key' => $landscapeKey],
                    [
                        'label' => $p['label'].' (Landscape)',
                        'platform' => 'android',
                        'category' => 'phone',
                        'form_factor' => 'android_phone_landscape',
                        'apple_tier' => null,
                        'export_w' => $p['export_h'],
                        'export_h' => $p['export_w'],
                        'frame_svg_path' => null,
                        // Safe area rotates 90° CCW: top→left, right→top, bottom→right, left→bottom.
                        'safe_area' => json_encode([
                            'top' => 0, 'right' => 80, 'bottom' => 0, 'left' => 48,
                        ]),
                        'family_id' => $p['family_id'],
                        'is_active' => true,
                        'created_at' => $now,
                        'updated_at' => $now,
                    ],
                );
            }

            // Rotation pairs.
            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,
                    ]);
                }
            }

            // Pixel 9 series cedes its family slots to Pixel 10.
            $pixel9Keys = [
                'android-pixel-9-pro', 'android-pixel-9-pro-landscape',
                'android-pixel-9', 'android-pixel-9-landscape',
            ];
            DB::table('device_presets')
                ->whereIn('key', $pixel9Keys)
                ->update(['family_id' => null, 'updated_at' => $now]);

            // Clear Pixel 9 Pro's real-frame flag — the manifest is being
            // repointed at Pixel 10 Pro in the same release.
            DB::table('device_presets')
                ->whereIn('key', ['android-pixel-9-pro', 'android-pixel-9-pro-landscape'])
                ->update([
                    'has_real_frame' => false,
                    'real_frame_color_options' => null,
                    'real_frame_screen_rect' => null,
                    'updated_at' => $now,
                ]);

            // Apply real-frame backfill inline for Pixel 10 Pro. Same idempotent
            // pattern as the iPhone 17 seed migration.
            $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'];
                        if (! str_starts_with($key, 'android-pixel-10')) {
                            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
    {
        $pixel10Keys = [
            'android-pixel-10-pro', 'android-pixel-10-pro-landscape',
            'android-pixel-10', 'android-pixel-10-landscape',
        ];

        DB::transaction(function () use ($pixel10Keys) {
            // Restore Pixel 9 family ownership before dropping Pixel 10.
            DB::table('device_presets')
                ->whereIn('key', ['android-pixel-9-pro', 'android-pixel-9-pro-landscape'])
                ->update(['family_id' => 'pro_max']);
            DB::table('device_presets')
                ->whereIn('key', ['android-pixel-9', 'android-pixel-9-landscape'])
                ->update(['family_id' => 'standard']);

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