<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LegalDocument;
use App\Support\LegalDocumentHtml;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Inertia\Response;

class LegalDocumentController extends Controller
{
    public function edit(): Response
    {
        return Inertia::render('admin/legal-documents', [
            'documents' => LegalDocument::configuredDocuments()
                ->map(fn (LegalDocument $document): array => [
                    'key' => $document->key,
                    'title' => $document->title,
                    'body' => LegalDocumentHtml::sanitize($document->body ?? ''),
                    'href' => route('legal-documents.show', $document),
                ])
                ->values(),
        ]);
    }

    public function update(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'documents' => ['required', 'array', 'size:3'],
            'documents.*.key' => ['required', 'string', 'distinct', Rule::in(LegalDocument::keys())],
            'documents.*.title' => ['required', 'string', 'max:120'],
            'documents.*.body' => ['nullable', 'string', 'max:500000'],
        ]);

        DB::transaction(function () use ($validated): void {
            foreach ($validated['documents'] as $document) {
                LegalDocument::query()->updateOrCreate(
                    ['key' => $document['key']],
                    [
                        'title' => $document['title'],
                        'body' => LegalDocumentHtml::sanitize($document['body'] ?? ''),
                    ],
                );
            }
        });

        Inertia::flash('toast', [
            'type' => 'success',
            'message' => 'Documentos legales guardados correctamente.',
        ]);

        return to_route('admin.legal-documents.edit');
    }
}
