<?php

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

return new class extends Migration
{
    /**
     * Walks every row and writes `rotation_pair_id` to point at its rotation
     * twin. Pairing rule is purely key-suffix based — a portrait `<base>` row
     * pairs with `<base>-landscape`, and vice versa — so future preset
     * additions auto-pair when this migration is replayed as a data backfill.
     * Rows without a twin (orphan presets) silently keep `rotation_pair_id`
     * null; the resolver treats null as "no rotation available" and falls
     * back to scaling the existing preset's frame.
     */
    public function up(): void
    {
        $rows = DB::table('device_presets')->select('id', 'key')->get();
        $idsByKey = [];
        foreach ($rows as $row) {
            $idsByKey[$row->key] = (int) $row->id;
        }

        DB::transaction(function () use ($rows, $idsByKey) {
            foreach ($rows as $row) {
                $pairKey = str_ends_with($row->key, '-landscape')
                    ? substr($row->key, 0, -strlen('-landscape'))
                    : $row->key . '-landscape';

                $pairId = $idsByKey[$pairKey] ?? null;
                if ($pairId === null) {
                    continue;
                }

                DB::table('device_presets')
                    ->where('id', $row->id)
                    ->update([
                        'rotation_pair_id' => $pairId,
                        'updated_at' => now(),
                    ]);
            }
        });
    }

    public function down(): void
    {
        DB::table('device_presets')->update([
            'rotation_pair_id' => null,
            'updated_at' => now(),
        ]);
    }
};
