<?php

namespace App\Modules\HR\Recruitment\DTOs;

final readonly class RecruitmentReportFilters
{
    public function __construct(
        public ?string $dateFrom = null,
        public ?string $dateTo = null,
        public ?int $departmentId = null,
        public ?int $vacancyId = null,
        public ?int $recruiterId = null,
        public ?string $status = null,
    ) {}

    /**
     * @param  array<string, mixed>  $data
     */
    public static function fromArray(array $data): self
    {
        return new self(
            dateFrom: self::str($data, 'date_from') ?? self::str($data, 'from'),
            dateTo: self::str($data, 'date_to') ?? self::str($data, 'to'),
            departmentId: self::intOrNull($data, 'department_id'),
            vacancyId: self::intOrNull($data, 'vacancy_id'),
            recruiterId: self::intOrNull($data, 'recruiter_id'),
            status: self::str($data, 'status'),
        );
    }

    /** @return array<string, string|int> */
    public function toQuery(): array
    {
        return array_filter([
            'date_from' => $this->dateFrom,
            'date_to' => $this->dateTo,
            'department_id' => $this->departmentId,
            'vacancy_id' => $this->vacancyId,
            'recruiter_id' => $this->recruiterId,
            'status' => $this->status,
        ], fn ($v) => $v !== null && $v !== '');
    }

    /** @param  array<string, mixed>  $data */
    private static function str(array $data, string $key): ?string
    {
        $v = $data[$key] ?? null;

        return $v !== null && $v !== '' ? (string) $v : null;
    }

    /** @param  array<string, mixed>  $data */
    private static function intOrNull(array $data, string $key): ?int
    {
        $v = $data[$key] ?? null;
        if ($v === null || $v === '') {
            return null;
        }

        return (int) $v;
    }
}
