<?php

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

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

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

    public function build(int $tenantId, RecruitmentReportFilters $filters): array
    {
        $rows = [];
        $openings = 0;
        $filled = 0;
        foreach ($this->reports->openVacancies($tenantId, $filters)->get() as $v) {
            $o = (int) $v->openings;
            $f = (int) $v->filled_positions;
            $openings += $o;
            $filled += $f;
            $rows[] = [
                $v->reference_code,
                $v->title,
                $v->department?->name,
                $v->position?->title,
                $o,
                $f,
                max(0, $o - $f),
                __('recruitment.vacancies.status.'.$v->status),
            ];
        }

        return [
            'title_key' => 'recruitment.reports.types.open_vacancies',
            'columns' => ['reference', 'title', 'department', 'position', 'openings', 'filled', 'remaining', 'status'],
            'rows' => $rows,
            'summary' => [
                'vacancies' => count($rows),
                'openings' => $openings,
                'filled' => $filled,
                'remaining' => max(0, $openings - $filled),
            ],
        ];
    }
}
