<?php

namespace App\Modules\HR\Recruitment\Services\ReportBuilders;

use App\Modules\HR\Recruitment\DTOs\RecruitmentReportFilters;
use App\Modules\HR\Recruitment\Repositories\RecruitmentReportRepository;
use App\Modules\HR\Recruitment\Support\ApplicationStatus;

class ApplicationsByStatusReportBuilder implements RecruitmentReportBuilder
{
    public function __construct(
        private readonly RecruitmentReportRepository $reports,
    ) {}

    public function build(int $tenantId, RecruitmentReportFilters $filters): array
    {
        $q = $this->reports->applicationsBase($tenantId, $filters)
            ->with(['candidate', 'vacancy'])
            ->orderByDesc('applied_at')
            ->limit(500);

        $rows = [];
        foreach ($q->get() as $app) {
            $rows[] = [
                $app->reference_code,
                $app->candidate?->full_name,
                $app->vacancy?->title,
                __('recruitment.applications.status.'.$app->status),
                $app->source,
                $app->applied_at?->format('Y-m-d'),
            ];
        }

        $counts = [];
        foreach (ApplicationStatus::all() as $status) {
            $counts[$status] = $this->reports->applicationsBase(
                $tenantId,
                new RecruitmentReportFilters(
                    dateFrom: $filters->dateFrom,
                    dateTo: $filters->dateTo,
                    departmentId: $filters->departmentId,
                    vacancyId: $filters->vacancyId,
                    recruiterId: $filters->recruiterId,
                    status: $status,
                )
            )->count();
        }

        return [
            'title_key' => 'recruitment.reports.types.applications_by_status',
            'columns' => ['reference', 'candidate', 'vacancy', 'status', 'source', 'applied_at'],
            'rows' => $rows,
            'summary' => $counts,
        ];
    }
}
