<?php

namespace App\Http\Controllers\Admin;

use App\Events\DocumentSettingsUpdated;
use App\Http\Controllers\Controller;
use App\Services\Documents\DocumentSettings as SettingsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Inertia\Inertia;

class DocumentSettingsController extends Controller
{
    public function edit(SettingsService $svc)
    {
        $this->authorizeAccess();
        $settings = $svc->get();

        return Inertia::render('Admin/DocumentSettings/Edit', [
            'settings' => $settings,
            'defaults' => [
                'file_name_pattern' => config('documents.file_name_pattern'),
                'date_format' => config('documents.date_format'),
                'unresolved_policy' => config('documents.unresolved_policy'),
            ],
        ]);
    }

    public function update(Request $request, SettingsService $svc)
    {
        $this->authorizeAccess();
        $data = $request->validate([
            'file_name_pattern' => ['required', 'string', 'max:255'],
            'date_format' => ['required', 'string', 'max:40'],
            'unresolved_policy' => ['required', 'in:fail,blank,keep'],
            'preview_enabled' => ['required', 'boolean'],
            'whitelist' => ['nullable', 'array'],
            'whitelist.*' => ['array'],
            'date_formats' => ['nullable', 'array'],
            'date_formats.*' => ['string'],
        ]);
        $settings = $svc->get();
        $settings->fill($data)->save();
        $svc->refresh();
        event(new DocumentSettingsUpdated($settings));

        return redirect()->back()->with('success', 'Nastavitve shranjene.');
    }

    private function authorizeAccess(): void
    {
        if (Gate::denies('manage-settings') && Gate::denies('manage-document-templates')) {
            abort(403);
        }
    }
}
