<?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;
use App\Modules\HR\Recruitment\Support\InterviewStatus;
use App\Modules\HR\Recruitment\Support\OfferLetterStatus;

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

    public function build(int $tenantId, RecruitmentReportFilters $filters): array
    {
        $apps = $this->reports->applicationsBase($tenantId, $this->withoutStatus($filters));
        $interviews = $this->reports->interviewsBase($tenantId, $this->withoutStatus($filters));
        $offers = $this->reports->offersBase($tenantId, $this->withoutStatus($filters));

        $stages = [
            'applications' => (clone $apps)->count(),
            'screening' => (clone $apps)->where('status', ApplicationStatus::SCREENING)->count(),
            'shortlisted' => (clone $apps)->where('status', ApplicationStatus::SHORTLISTED)->count(),
            'interviews' => (clone $interviews)->where('status', '!=', InterviewStatus::CANCELLED)->count(),
            'offers_sent' => (clone $offers)->whereIn('status', [
                OfferLetterStatus::SENT, OfferLetterStatus::ACCEPTED, OfferLetterStatus::HIRED,
                OfferLetterStatus::REJECTED, OfferLetterStatus::EXPIRED,
            ])->count(),
            'offers_accepted' => (clone $offers)->whereIn('status', [
                OfferLetterStatus::ACCEPTED, OfferLetterStatus::HIRED,
            ])->count(),
            'hired' => (clone $apps)->where('status', ApplicationStatus::HIRED)->count(),
        ];

        $rows = [];
        foreach ($stages as $key => $count) {
            $rows[] = [__('recruitment.reports.funnel.stages.'.$key), $count];
        }

        return [
            'title_key' => 'recruitment.reports.types.funnel',
            'columns' => ['stage', 'count'],
            'rows' => $rows,
            'summary' => $stages,
        ];
    }

    private function withoutStatus(RecruitmentReportFilters $f): RecruitmentReportFilters
    {
        return new RecruitmentReportFilters(
            dateFrom: $f->dateFrom,
            dateTo: $f->dateTo,
            departmentId: $f->departmentId,
            vacancyId: $f->vacancyId,
            recruiterId: $f->recruiterId,
            status: null,
        );
    }
}
