<?php

namespace App\Modules\HR\Positions\DTOs;

final readonly class PositionWriteData
{
    public function __construct(
        public string $title,
        public int $departmentId,
        public string $salary,
        public ?string $description,
        public bool $isActive,
        public ?int $jobGradeId,
        public ?string $responsibilities,
        public ?string $requiredSkills,
        public ?string $minSalary,
        public ?string $maxSalary,
        public ?string $kpis,
        public ?string $requiredTraining,
        public ?string $careerPath,
    ) {}

    /**
     * @param  array{title: string, department_id: int, salary: numeric|string, description?: ?string, is_active?: bool}  $data
     */
    public static function fromValidated(array $data): self
    {
        $description = $data['description'] ?? null;

        return new self(
            title: (string) $data['title'],
            departmentId: (int) $data['department_id'],
            salary: (string) $data['salary'],
            description: $description !== null && $description !== '' ? (string) $description : null,
            isActive: (bool) ($data['is_active'] ?? true),
            jobGradeId: isset($data['job_grade_id']) ? (int) $data['job_grade_id'] : null,
            responsibilities: self::nullableString($data, 'responsibilities'),
            requiredSkills: self::nullableString($data, 'required_skills'),
            minSalary: self::nullableString($data, 'min_salary'),
            maxSalary: self::nullableString($data, 'max_salary'),
            kpis: self::nullableString($data, 'kpis'),
            requiredTraining: self::nullableString($data, 'required_training'),
            careerPath: self::nullableString($data, 'career_path'),
        );
    }

    /**
     * @return array{title: string, department_id: int, salary: string, description: ?string, is_active: bool}
     */
    public function toArray(): array
    {
        return [
            'title' => $this->title,
            'department_id' => $this->departmentId,
            'salary' => $this->salary,
            'description' => $this->description,
            'is_active' => $this->isActive,
            'job_grade_id' => $this->jobGradeId,
            'responsibilities' => $this->responsibilities,
            'required_skills' => $this->requiredSkills,
            'min_salary' => $this->minSalary,
            'max_salary' => $this->maxSalary,
            'kpis' => $this->kpis,
            'required_training' => $this->requiredTraining,
            'career_path' => $this->careerPath,
        ];
    }

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

        return $value === null || $value === '' ? null : (string) $value;
    }
}
