<?php

declare(strict_types=1);

namespace TekDek\Employees;

/**
 * Controller for employee API endpoints.
 */
class EmployeeController
{
    private EmployeeRepository $repository;

    public function __construct(?EmployeeRepository $repository = null)
    {
        $this->repository = $repository ?? new EmployeeRepository();
    }

    /**
     * GET /api/employees — List all employees.
     */
    public function index(): void
    {
        $employees = $this->repository->getAll();

        $this->json(200, [
            'success' => true,
            'data'    => $employees,
            'count'   => count($employees),
        ]);
    }

    /**
     * GET /api/employees/:slug — Get single employee.
     */
    public function show(string $slug): void
    {
        // Validate slug format: lowercase alphanumeric + hyphens, 1-50 chars
        if (!preg_match('/^[a-z0-9](?:[a-z0-9-]{0,48}[a-z0-9])?$/', $slug)) {
            $this->json(400, [
                'success' => false,
                'error'   => 'Invalid slug format. Use lowercase letters, numbers, and hyphens (1-50 chars).',
            ]);
            return;
        }

        $employee = $this->repository->getBySlug($slug);

        if ($employee === null) {
            $this->json(404, [
                'success' => false,
                'error'   => "Employee '{$slug}' not found.",
            ]);
            return;
        }

        $this->json(200, [
            'success' => true,
            'data'    => $employee,
        ]);
    }

    /**
     * Send a JSON response.
     */
    private function json(int $statusCode, array $data): void
    {
        http_response_code($statusCode);
        echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    }
}
