<?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\OfferLetterStatus;

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

    public function build(int $tenantId, RecruitmentReportFilters $filters): array
    {
        $base = $this->reports->offersBase($tenantId, new RecruitmentReportFilters(
            dateFrom: $filters->dateFrom,
            dateTo: $filters->dateTo,
            departmentId: $filters->departmentId,
            vacancyId: $filters->vacancyId,
            recruiterId: $filters->recruiterId,
            status: null,
        ));

        $sentLike = [
            OfferLetterStatus::SENT,
            OfferLetterStatus::ACCEPTED,
            OfferLetterStatus::HIRED,
            OfferLetterStatus::REJECTED,
            OfferLetterStatus::EXPIRED,
            OfferLetterStatus::WITHDRAWN,
        ];
        $sent = (clone $base)->whereIn('status', $sentLike)->count();
        $accepted = (clone $base)->whereIn('status', [
            OfferLetterStatus::ACCEPTED, OfferLetterStatus::HIRED,
        ])->count();
        $rejected = (clone $base)->where('status', OfferLetterStatus::REJECTED)->count();
        $rate = $sent > 0 ? round(($accepted / $sent) * 100, 1) : 0.0;

        $rows = [
            [__('recruitment.reports.offer_acceptance.sent'), $sent],
            [__('recruitment.reports.offer_acceptance.accepted'), $accepted],
            [__('recruitment.reports.offer_acceptance.rejected'), $rejected],
            [__('recruitment.reports.offer_acceptance.rate'), $rate.'%'],
        ];

        return [
            'title_key' => 'recruitment.reports.types.offer_acceptance',
            'columns' => ['metric', 'value'],
            'rows' => $rows,
            'summary' => [
                'sent' => $sent,
                'accepted' => $accepted,
                'rejected' => $rejected,
                'rate' => $rate,
            ],
        ];
    }
}
