<?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\AdminCurrencyStoreRequest;

final class AdminCurrencyStoreController extends Controller
{
    public function __invoke(
        AdminCurrencyStoreRequest $request,
        CurrencyActivationService $activationService,
    ): JsonResponse {
        $data = $request->validated();
        $enabled = (bool) ($data['is_enabled'] ?? true);
        $bettable = $enabled && (bool) ($data['is_bettable'] ?? false);

        $currency = DB::transaction(function () use ($data, $enabled, $bettable, $activationService): Currency {
            $currency = Currency::query()->create([
                'code' => $data['code'],
                'name' => $data['name'],
                'decimal_places' => 2,
                'is_enabled' => $enabled,
                'is_bettable' => $bettable,
            ]);

            $activationService->ensureBettableCurrencyReady($currency);

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

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

    /** @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(),
        ];
    }
}
