<?php

namespace App\Http\Controllers;

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

class DevInspectorController extends Controller
{
    public function store(Request $request)
    {
        abort_unless(app()->isLocal(), 404);

        $data = $request->validate([
            'url' => ['nullable', 'string', 'max:1000'],
            'selector' => ['required', 'string', 'max:1200'],
            'tag' => ['required', 'string', 'max:80'],
            'id' => ['nullable', 'string', 'max:160'],
            'classes' => ['nullable', 'array'],
            'classes.*' => ['string', 'max:160'],
            'text' => ['nullable', 'string', 'max:1200'],
            'rect' => ['nullable', 'array'],
            'path' => ['nullable', 'array'],
            'path.*' => ['string', 'max:240'],
        ]);

        $data['captured_at'] = now()->toIso8601String();

        File::ensureDirectoryExists(storage_path('app/dev-inspector'));
        File::put(
            storage_path('app/dev-inspector/last-selection.json'),
            json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
        );

        return response()->json(['ok' => true]);
    }
}
