<?php

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

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

/** GET /api/v1/admin/reconcile-jobs */
final class ReconcileJobIndexController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        $p = AdminApiList::readPaging($request);
        $type = trim((string) $request->query('reconcile_type', ''));

        $q = ReconcileJob::query()->orderByDesc('id');
        if ($type !== '') {
            $q->where('reconcile_type', $type);
        }

        AdminReconcileScope::applyToJobsQuery($q, $admin);

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

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

    /** @return array<string, mixed> */
    private function row(ReconcileJob $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,
            'reconcile_type' => $j->reconcile_type,
            'status' => $j->status,
            'period_start' => $j->period_start?->toIso8601String(),
            'period_end' => $j->period_end?->toIso8601String(),
            'summary_json' => $j->summary_json,
            'finished_at' => $j->finished_at?->toIso8601String(),
            'created_at' => $j->created_at?->toIso8601String(),
        ];
    }
}
