<?php

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

use App\Models\AdminUser;
use App\Lottery\ErrorCode;
use App\Support\ApiMessage;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use App\Models\RiskCapVersion;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Lottery\ConfigVersionStatus;
use App\Support\AdminConfigPresenter;
use App\Services\Config\RiskCapStreamService;

/** PUT /api/v1/admin/config/risk-cap-versions/{id}/items */
final class RiskCapItemsReplaceController extends Controller
{
    public function __invoke(Request $request, int $id, RiskCapStreamService $service): JsonResponse
    {
        /** @var AdminUser $admin */
        $admin = $request->lotteryAdmin();

        /** @var RiskCapVersion $version */
        $version = RiskCapVersion::query()->whereKey($id)->firstOrFail();

        if ($version->status !== ConfigVersionStatus::Draft->value) {
            return ApiResponse::error(
                ApiMessage::get($request, 'config_version_not_draft'),
                ErrorCode::ConfigVersionNotDraft->value,
                null,
                400,
            );
        }

        $data = $request->validate([
            'items' => ['required', 'array', 'min:1'],
            'items.*.draw_id' => ['sometimes', 'nullable', 'integer', 'exists:draws,id'],
            'items.*.normalized_number' => ['required', 'string', 'size:4', 'regex:/^[0-9]{4}$/'],
            'items.*.cap_amount' => ['required', 'integer', 'min:1'],
            'items.*.cap_type' => ['required', 'string', 'in:default,per_number'],
        ]);

        $service->replaceItems($version, $data['items'], $admin);

        return ApiResponse::success(
            AdminConfigPresenter::riskCapVersionDetail($version->fresh()->load('items')),
        );
    }
}
