<?php

namespace App\Http\Controllers\Api\V1\Admin\Currency;

use App\Models\Currency;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Services\Currency\CurrencyActivationService;
use App\Http\Requests\Admin\AdminCurrencyUpdateRequest;

final class AdminCurrencyUpdateController extends Controller
{
    public function __invoke(
        AdminCurrencyUpdateRequest $request,
        Currency $currency,
        CurrencyActivationService $activationService,
    ): JsonResponse {
        $data = $request->validated();

        if (array_key_exists('is_enabled', $data) && ! (bool) $data['is_enabled']) {
            $data['is_bettable'] = false;
        } elseif (array_key_exists('is_bettable', $data)) {
            $data['is_bettable'] = (bool) $data['is_bettable'];
        }

        if (array_key_exists('is_enabled', $data)) {
            $data['is_enabled'] = (bool) $data['is_enabled'];
        }

        $currency = DB::transaction(function () use ($currency, $data, $activationService): Currency {
            $currency->fill($data);
            $currency->save();

            $activationService->ensureBettableCurrencyReady($currency);

            return $currency->fresh();
        });

        return ApiResponse::success($this->serializeCurrency($currency));
    }

    /** @return array<string, mixed> */
    private function serializeCurrency(Currency $currency): array
    {
        return [
            'id' => (int) $currency->id,
            'code' => $currency->code,
            'name' => $currency->name,
            'decimal_places' => (int) $currency->decimal_places,
            'is_enabled' => (bool) $currency->is_enabled,
            'is_bettable' => (bool) $currency->is_bettable,
            'created_at' => $currency->created_at?->toIso8601String(),
            'updated_at' => $currency->updated_at?->toIso8601String(),
        ];
    }
}
