<?php

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

use App\Modules\HR\Recruitment\DTOs\RecruitmentReportFilters;
use App\Modules\HR\Recruitment\Repositories\RecruitmentReportRepository;
use Carbon\Carbon;

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

    public function build(int $tenantId, RecruitmentReportFilters $filters): array
    {
        $daysList = [];
        $rows = [];
        $apps = $this->reports->applicationsBase($tenantId, $filters)
            ->whereNotNull('hired_at')
            ->whereNotNull('applied_at')
            ->with(['candidate', 'vacancy', 'employee'])
            ->orderByDesc('hired_at')
            ->limit(500)
            ->get();

        foreach ($apps as $app) {
            $days = Carbon::parse($app->applied_at)->startOfDay()
                ->diffInDays(Carbon::parse($app->hired_at)->startOfDay());
            $daysList[] = $days;
            $rows[] = [
                $app->reference_code,
                $app->candidate?->full_name,
                $app->vacancy?->title,
                $app->applied_at?->format('Y-m-d'),
                $app->hired_at?->format('Y-m-d'),
                $days,
            ];
        }

        sort($daysList);
        $count = count($daysList);
        $avg = $count > 0 ? round(array_sum($daysList) / $count, 1) : 0;
        $median = $count > 0 ? $daysList[(int) floor(($count - 1) / 2)] : 0;

        return [
            'title_key' => 'recruitment.reports.types.time_to_hire',
            'columns' => ['reference', 'candidate', 'vacancy', 'applied_at', 'hired_at', 'days'],
            'rows' => $rows,
            'summary' => [
                'hires' => $count,
                'avg_days' => $avg,
                'median_days' => $median,
                'min_days' => $count > 0 ? min($daysList) : 0,
                'max_days' => $count > 0 ? max($daysList) : 0,
            ],
        ];
    }
}
