<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\BirthdayReportRequest;
use App\Http\Resources\MemberRowResource;
use App\Models\Member;
use Illuminate\Http\JsonResponse;

class ReportController extends Controller
{
    public function birthdays(BirthdayReportRequest $request): JsonResponse
    {
        // whereMonth()/DAYOFMONTH() wrap date_of_birth in a function, which
        // isn't sargable (forces a full scan) and isn't safe to combine with
        // cursorPaginate() cursors anyway. Sort and filter on the generated
        // date_of_birth_month_day column instead — 'MM-DD' string order
        // matches calendar order within a fixed month, and stays on an index.
        $month = str_pad((string) $request->integer('month'), 2, '0', STR_PAD_LEFT);

        $query = Member::visibleTo($request->user())
            ->with('branch:id,name,code')
            ->where('date_of_birth_month_day', 'like', "{$month}-%")
            ->orderBy('date_of_birth_month_day')
            ->orderBy('id');

        if ($request->filled('branch_id')) {
            $query->where('branch_id', $request->integer('branch_id'));
        }

        $perPage = (int) ($request->integer('per_page') ?: 25);
        $members = $query->cursorPaginate($perPage)->withQueryString();

        return MemberRowResource::collection($members)->response();
    }
}
