<?php

declare(strict_types=1);

namespace TekDek\Employees;

use PDO;

/**
 * Repository for employee data access.
 */
class EmployeeRepository
{
    private PDO $db;

    public function __construct(?PDO $db = null)
    {
        $this->db = $db ?? Database::getConnection();
    }

    /**
     * Get all employees sorted by sort_order.
     *
     * @return array<int, array<string, mixed>>
     */
    public function getAll(): array
    {
        $stmt = $this->db->query(
            'SELECT * FROM employees ORDER BY sort_order ASC, name ASC'
        );
        $rows = $stmt->fetchAll();
        return array_map([$this, 'formatRow'], $rows);
    }

    /**
     * Get a single employee by slug.
     *
     * @return array<string, mixed>|null
     */
    public function getBySlug(string $slug): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM employees WHERE slug = :slug LIMIT 1');
        $stmt->execute(['slug' => $slug]);
        $row = $stmt->fetch();
        return $row ? $this->formatRow($row) : null;
    }

    /**
     * Format a database row for API output.
     *
     * @param array<string, mixed> $row
     * @return array<string, mixed>
     */
    private function formatRow(array $row): array
    {
        // Decode JSON skills field
        if (isset($row['skills']) && is_string($row['skills'])) {
            $row['skills'] = json_decode($row['skills'], true) ?? [];
        }

        // Cast numeric fields
        $row['sort_order'] = (int) ($row['sort_order'] ?? 0);

        return $row;
    }
}
