<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('_dev/session', function (Request $request) {
    // ✅ local / debug에서만 허용
    abort_unless(config('app.debug') || app()->environment('local'), 404);

    // ✅ (권장) POST에 간단 토큰 체크 (실수로 노출 방지)
    // .env: DEV_LAB_TOKEN="something"
    $token = (string) $request->input('_dev_token', '');
    abort_unless($token !== '' && hash_equals((string) env('DEV_LAB_TOKEN', ''), $token), 404);

    $action = (string) $request->input('_dev_sess_action', '');

    $parse = function (string $raw) {
        $s = trim($raw);
        $lower = strtolower($s);

        if ($lower === 'true')  return true;
        if ($lower === 'false') return false;
        if ($lower === 'null')  return null;

        if (preg_match('/^-?\d+$/', $s)) {
            $int = (int) $s;
            if ((string) $int === $s) return $int;
        }

        if (preg_match('/^-?\d+\.\d+$/', $s)) {
            return (float) $s;
        }

        if ($s !== '' && (str_starts_with($s, '{') || str_starts_with($s, '['))) {
            $j = json_decode($s, true);
            if (json_last_error() === JSON_ERROR_NONE) return $j;
        }

        return $raw;
    };

    if ($action === 'flush') {
        session()->flush();
        session()->save();

    } elseif ($action === 'put') {
        $k = trim((string) $request->input('_dev_sess_key', ''));
        $raw = (string) $request->input('_dev_sess_value', '');

        if ($k !== '') {
            session()->put($k, $parse($raw));
            session()->save();
        }
    }

    return redirect()->to((string) $request->input('_dev_return', '/'));
})->name('admin.dev.session');
