<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Services\System\SettingsService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AdminSettingsController extends Controller
{
    public function __construct(private readonly SettingsService $settings) {}

    private function authorizeAdmin(Request $request): ?JsonResponse
    {
        $token = (string) config('dewemoji.admin.token', '');
        $provided = trim((string) $request->header('X-Admin-Token', ''));
        if ($token === '' || $provided === '' || ! hash_equals($token, $provided)) {
            return response()->json(['ok' => false, 'error' => 'unauthorized'], 401);
        }

        return null;
    }

    public function index(Request $request): JsonResponse
    {
        if ($res = $this->authorizeAdmin($request)) {
            return $res;
        }

        $keys = $request->query('keys');
        $all = $this->settings->all();
        if (is_string($keys) && $keys !== '') {
            $filter = array_filter(array_map('trim', explode(',', $keys)));
            $all = array_intersect_key($all, array_flip($filter));
        }

        return response()->json(['ok' => true, 'settings' => $all]);
    }

    public function update(Request $request): JsonResponse
    {
        if ($res = $this->authorizeAdmin($request)) {
            return $res;
        }

        $payload = $request->input('settings');
        if (! is_array($payload)) {
            return response()->json(['ok' => false, 'error' => 'invalid_payload'], 422);
        }

        $adminRef = (string) $request->header('X-Admin-Ref', '');
        $this->settings->setMany($payload, $adminRef !== '' ? $adminRef : null);

        return response()->json([
            'ok' => true,
            'settings' => $this->settings->all(),
        ]);
    }
}
