<?php

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

/**
 * Backfills the three real-frame columns on `device_presets` from
 * public/device-frames/manifest.json. Each manifest entry's `device_preset_id`
 * is matched against the `key` column; matches flip `has_real_frame = true`
 * and persist the color + screen-rect JSON.
 *
 * The manifest file is dropped in alongside the frame PNG assets in Phase 1B.
 * Until those assets land (fresh install or self-hosted ZIP that predates the
 * asset bundle) the migration logs a notice and returns — DO NOT fail. Once
 * the assets arrive the operator can re-run via a dated follow-up migration.
 */
return new class extends Migration
{
    public function up(): void
    {
        $manifestPath = public_path('device-frames/manifest.json');

        if (! is_file($manifestPath)) {
            Log::info('[real-frames] manifest.json not present at '.$manifestPath.' — skipping backfill.');

            return;
        }

        $raw = file_get_contents($manifestPath);
        if ($raw === false) {
            Log::warning('[real-frames] manifest.json present but unreadable at '.$manifestPath.' — skipping backfill.');

            return;
        }

        $manifest = json_decode($raw, true);
        if (! is_array($manifest) || ! isset($manifest['frames']) || ! is_array($manifest['frames'])) {
            Log::warning('[real-frames] manifest.json malformed — missing frames[] — skipping backfill.');

            return;
        }

        DB::transaction(function () use ($manifest) {
            foreach ($manifest['frames'] as $frame) {
                if (! is_array($frame) || empty($frame['device_preset_id'])) {
                    continue;
                }

                $key = $frame['device_preset_id'];
                $colors = $frame['colors'] ?? null;
                $screenRect = $frame['screen_rect'] ?? null;

                // Each device has separate `device_presets` rows for portrait
                // and landscape orientations (e.g. `iphone-16-pro-max` +
                // `iphone-16-pro-max-landscape`). The manifest stores one entry
                // per device-family with both orientations under `screen_rect`,
                // so the backfill fans out to both rows. The portrait key
                // matches the manifest's `device_preset_id` directly; the
                // landscape variant is the same key with `-landscape` suffix.
                $payload = [
                    'has_real_frame' => true,
                    'real_frame_color_options' => $colors !== null ? json_encode($colors) : null,
                    'real_frame_screen_rect' => $screenRect !== null ? json_encode($screenRect) : null,
                    'updated_at' => now(),
                ];

                DB::table('device_presets')
                    ->whereIn('key', [$key, $key.'-landscape'])
                    ->update($payload);
            }
        });
    }

    public function down(): void
    {
        // Non-reversible — clearing the columns would also wipe any manual
        // tweaks an admin made post-backfill. The schema migration's down()
        // drops the columns wholesale; nothing to undo here.
    }
};
