<?php

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

use App\Models\AdminUser;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Support\AdminReportJobPolicy;
use App\Services\Admin\AdminReportJobService;
use App\Http\Requests\Admin\ReportJobStoreRequest;

/** POST /api/v1/admin/report-jobs */
final class ReportJobStoreController extends Controller
{
    public function __invoke(ReportJobStoreRequest $request, AdminReportJobService $service): JsonResponse
    {
        /** @var AdminUser $admin */
        $admin = $request->lotteryAdmin();

        $data = $request->validated();
        abort_unless(
            AdminReportJobPolicy::canExportReportType($admin, (string) $data['report_type']),
            403,
        );

        $job = $service->enqueue(
            $admin,
            $request,
            (string) $data['report_type'],
            (string) ($data['export_format'] ?? 'csv'),
            isset($data['filter_json']) ? (array) $data['filter_json'] : null,
        );

        return ApiResponse::success([
            'id' => (int) $job->id,
            'job_no' => $job->job_no,
            'report_type' => $job->report_type,
            'export_format' => $job->export_format,
            'status' => $job->status,
        ]);
    }
}
