<?php

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

use Carbon\Carbon;
use App\Models\AdminUser;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Services\Admin\AdminReconcileJobService;
use App\Http\Requests\Admin\ReconcileJobStoreRequest;

/** POST /api/v1/admin/reconcile-jobs */
final class ReconcileJobStoreController extends Controller
{
    public function __invoke(ReconcileJobStoreRequest $request, AdminReconcileJobService $service): JsonResponse
    {
        /** @var AdminUser $admin */
        $admin = $request->lotteryAdmin();

        $data = $request->validated();
        $items = $data['items'] ?? null;
        if (! is_array($items)) {
            $items = null;
        }

        $job = $service->createJob(
            $admin,
            $request,
            (string) ($data['reconcile_type'] ?? 'wallet_transfer'),
            isset($data['period_start'])
                ? Carbon::parse((string) $data['period_start'])
                : (isset($data['date_from']) ? Carbon::parse((string) $data['date_from'])->startOfDay() : null),
            isset($data['period_end'])
                ? Carbon::parse((string) $data['period_end'])
                : (isset($data['date_to']) ? Carbon::parse((string) $data['date_to'])->endOfDay() : null),
            $items,
            isset($data['player_id']) ? (int) $data['player_id'] : null,
        );

        return ApiResponse::success([
            'id' => (int) $job->id,
            'job_no' => $job->job_no,
            'status' => $job->status,
            'summary_json' => $job->summary_json,
            'item_count' => $job->items()->count(),
        ]);
    }
}
