<?php

namespace App\Http\Controllers;

use App\Facades\Settings;
use App\Http\Requests\UpdateDisplayCurrenciesRequest;
use Illuminate\Http\JsonResponse;
use Mtc\MercuryDataModels\Currency;

class CurrencyController extends Controller
{
    private const DISPLAY_SETTING_KEY = 'display-currencies';

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return Currency::all();
    }

    public function displaySettings(): JsonResponse
    {
        $currencies = Currency::query()->orderBy('code')->get(['code']);
        $data = Settings::getData(self::DISPLAY_SETTING_KEY);
        $enabled = $data['enabled'] ?? $currencies->pluck('code')->all();

        return response()->json([
            'currencies' => $currencies->map(fn (Currency $currency) => [
                'code' => $currency->code,
                'enabled' => in_array($currency->code, $enabled, true),
            ])->values(),
            'enabled' => array_values($enabled),
        ]);
    }

    public function updateDisplaySettings(UpdateDisplayCurrenciesRequest $request): JsonResponse
    {
        $validCodes = Currency::query()->pluck('code')->all();
        $enabled = array_values(array_intersect($request->input('enabled', []), $validCodes));

        Settings::setData(self::DISPLAY_SETTING_KEY, ['enabled' => $enabled]);

        return response()->json(['enabled' => $enabled]);
    }
}
