<?php

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

use App\Models\AdminUser;
use App\Lottery\ErrorCode;
use App\Support\ApiMessage;
use App\Support\ApiResponse;
use App\Models\SettlementBatch;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\SettlementBatchReviewRequest;
use App\Services\Settlement\SettlementBatchWorkflowService;

final class AdminSettlementBatchApproveController extends Controller
{
    public function __construct(private readonly SettlementBatchWorkflowService $service) {}

    public function __invoke(SettlementBatchReviewRequest $request, SettlementBatch $batch): JsonResponse
    {
        $admin = $request->user();
        if (! $admin instanceof AdminUser) {
            return ApiResponse::error(trans('admin.unauthenticated'), ErrorCode::AdminUnauthenticated->value, null, 401);
        }

        try {
            $updated = $this->service->approve($batch, $admin, $request->validated('remark') ?? null);
        } catch (\RuntimeException $e) {
            return ApiMessage::runtimeErrorResponse($request, $e);
        }

        return ApiResponse::success([
            'id' => (int) $updated->id,
            'status' => $updated->status,
            'review_status' => $updated->review_status,
        ]);
    }
}
