<?php

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

use App\Http\Controllers\Controller;
use App\Models\ReportJob;
use App\Support\AdminApiList;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/** GET /api/v1/admin/report-jobs */
final class ReportJobIndexController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $p = AdminApiList::readPaging($request);
        $reportType = trim((string) $request->query('report_type', ''));

        $query = ReportJob::query()
            ->orderByDesc('id');

        if ($reportType !== '') {
            $query->where('report_type', $reportType);
        }

        $paginator = $query->paginate($p['perPage'], ['*'], 'page', $p['page']);

        return AdminApiList::json($paginator, fn (ReportJob $j) => $this->row($j));
    }

    /** @return array<string, mixed> */
    private function row(ReportJob $j): array
    {
        return [
            'id' => (int) $j->id,
            'job_no' => $j->job_no,
            'admin_user_id' => $j->admin_user_id !== null ? (int) $j->admin_user_id : null,
            'report_type' => $j->report_type,
            'export_format' => $j->export_format,
            'status' => $j->status,
            'finished_at' => $j->finished_at?->toIso8601String(),
            'created_at' => $j->created_at?->toIso8601String(),
        ];
    }
}
