<?php

namespace App\Modules\HR\Payroll\DTOs;

final readonly class SalaryStructureWriteData
{
    /**
     * @param  list<array{id: ?int, code: ?string, name: string, component_type: string, calculation: string, amount: float, is_taxable: bool, sort_order: int}>  $components
     */
    public function __construct(
        public string $code,
        public string $name,
        public ?string $description,
        public string $currency,
        public bool $isActive,
        public array $components,
    ) {}

    /**
     * @param  array<string, mixed>  $data
     */
    public static function fromValidated(array $data): self
    {
        $components = [];
        foreach ($data['components'] ?? [] as $row) {
            $components[] = [
                'id' => isset($row['id']) && $row['id'] !== '' ? (int) $row['id'] : null,
                'code' => isset($row['code']) && $row['code'] !== '' ? (string) $row['code'] : null,
                'name' => (string) $row['name'],
                'component_type' => (string) $row['component_type'],
                'calculation' => (string) $row['calculation'],
                'amount' => (float) $row['amount'],
                'is_taxable' => (bool) ($row['is_taxable'] ?? false),
                'sort_order' => isset($row['sort_order']) ? (int) $row['sort_order'] : 0,
            ];
        }

        return new self(
            code: (string) $data['code'],
            name: (string) $data['name'],
            description: isset($data['description']) && $data['description'] !== '' ? (string) $data['description'] : null,
            currency: strtoupper((string) $data['currency']),
            isActive: (bool) ($data['is_active'] ?? true),
            components: $components,
        );
    }

    /**
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'code' => $this->code,
            'name' => $this->name,
            'description' => $this->description,
            'currency' => $this->currency,
            'is_active' => $this->isActive,
        ];
    }
}
