<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\Config\StoreConfigRequest;
use App\Http\Requests\Config\UpdateConfigRequest;
use App\Models\ChecklistConfig;
use App\Services\ChecklistConfigService;
use App\Traits\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ChecklistConfigController extends Controller
{
    use ApiResponse;

    public function __construct(private readonly ChecklistConfigService $configService) {}

    public function index(): JsonResponse
    {
        $configs = $this->configService->list();

        return $this->success($configs, 'Checklist configs retrieved');
    }

    public function store(StoreConfigRequest $request): JsonResponse
    {
        $config = $this->configService->create($request->validated(), $request->user());

        return $this->created($config, 'Config created successfully');
    }

    public function update(UpdateConfigRequest $request, int $id): JsonResponse
    {
        $config  = ChecklistConfig::findOrFail($id);
        $updated = $this->configService->update($config, $request->validated());

        return $this->success($updated, 'Config updated successfully');
    }

    public function destroy(Request $request, int $id): JsonResponse
    {
        if (! $request->user()->isAdmin()) {
            return $this->forbidden();
        }

        $config = ChecklistConfig::findOrFail($id);
        $this->configService->delete($config);

        return $this->noContent('Config deleted successfully');
    }

    public function reorder(Request $request): JsonResponse
    {
        if (! $request->user()->isAdmin()) {
            return $this->forbidden();
        }

        $request->validate([
            'items'              => ['required', 'array', 'min:1'],
            'items.*.id'         => ['required', 'integer', 'exists:checklist_configs,id'],
            'items.*.sort_order' => ['required', 'integer', 'min:0'],
        ]);

        $this->configService->reorder($request->input('items'));

        return $this->success(
            $this->configService->list(),
            'Fields reordered successfully'
        );
    }
}
