<?php

namespace App\Http\Controllers;

use App\Models\Label;
use App\Models\Macro;
use App\Models\MacroAssignment;
use App\Models\MacroCollection;
use App\Models\Setting;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class SettingsController extends Controller
{
    private const AGENDA_KEYS = [
        'agenda_start_title',
        'agenda_end_title',
        'agenda_announcement_position',
        'agenda_sermon_matching',
    ];

    public function index(): Response
    {
        $settings = [];
        foreach (self::AGENDA_KEYS as $key) {
            $settings[$key] = Setting::get($key);
        }

        return Inertia::render('Settings', [
            'settings' => $settings,
            'assignments' => MacroAssignment::with(['macro', 'label'])->orderBy('part_type')->orderBy('order')->get(),
            'macros' => Macro::with('collections')->orderBy('name')->get(),
            'labels' => Label::orderBy('name')->get(),
            'collections' => MacroCollection::with('macros')->orderBy('name')->get(),
            'last_macros_import' => [
                'at' => Setting::get('macros_last_imported_at'),
                'filename' => Setting::get('macros_last_imported_filename'),
            ],
            'last_labels_import' => [
                'at' => Setting::get('labels_last_imported_at'),
                'filename' => Setting::get('labels_last_imported_filename'),
            ],
        ]);
    }

    public function update(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'key' => ['required', 'string', 'in:'.implode(',', self::AGENDA_KEYS)],
            'value' => ['nullable', 'string', 'max:500'],
        ]);

        Setting::set($validated['key'], $validated['value']);

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