<?php

namespace App\Http\Controllers\Api\Settings;

use App\Http\Controllers\Api\Core\BaseApiController;
use App\Http\Requests\Settings\ConfigurationStoreRequest;
use App\Http\Requests\Settings\ConfigurationUpdateRequest;
use App\Http\Resources\Settings\ConfigurationResource;
use App\Services\Settings\ConfigurationService;
use Illuminate\Http\JsonResponse;

class ConfigurationAdminController extends BaseApiController
{
    public function __construct(private ConfigurationService $service)
    {
        parent::__construct();
    }

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

        return response()->json([
            'ok' => true,
            'configs' => ConfigurationResource::collection($configs),
        ]);
    }

    public function store(ConfigurationStoreRequest $request): JsonResponse
    {
        $config = $this->service->store($request->validated());

        return response()->json([
            'ok' => true,
            'config' => new ConfigurationResource($config->toArray()),
        ], 201);
    }

    public function update(ConfigurationUpdateRequest $request, int $id): JsonResponse
    {
        $config = $this->service->update($id, $request->validated());
        if (!$config) {
            return response()->json(['ok' => false, 'message' => 'Configuration not found.'], 404);
        }

        return response()->json([
            'ok' => true,
            'config' => new ConfigurationResource($config->toArray()),
        ]);
    }

    public function destroy(int $id): JsonResponse
    {
        $deleted = $this->service->delete($id);
        if (!$deleted) {
            return response()->json(['ok' => false, 'message' => 'Configuration not found.'], 404);
        }

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

    public function getByKey(string $configKey): JsonResponse
    {
        $config = $this->service->getByKey($configKey);
        if (!$config) {
            return response()->json(['ok' => false, 'message' => 'Configuration not found.'], 404);
        }

        return response()->json([
            'ok' => true,
            'config' => new ConfigurationResource($config->toArray()),
        ]);
    }
}
