<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Repositories\UsuarioRepository;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class UsuarioController
{
    private UsuarioRepository $usuarios;

    public function __construct(UsuarioRepository $usuarios)
    {
        $this->usuarios = $usuarios;
    }

    public function listarPorRol(Request $request, Response $response, array $args): Response
    {
        $rol = (string) $args['rol'];

        if (!in_array($rol, ['admin', 'tienda', 'repartidor', 'cliente'], true)) {
            return $this->json($response, ['error' => 'Rol inválido'], 422);
        }

        return $this->json($response, $this->usuarios->listarPorRol($rol));
    }

    public function crear(Request $request, Response $response): Response
    {
        $body = (array) $request->getParsedBody();

        foreach (['nombre', 'email', 'password', 'rol'] as $campo) {
            if (empty($body[$campo])) {
                return $this->json($response, ['error' => "El campo {$campo} es requerido"], 422);
            }
        }

        if (!in_array($body['rol'], ['admin', 'tienda', 'repartidor', 'cliente'], true)) {
            return $this->json($response, ['error' => 'Rol inválido'], 422);
        }

        if ($this->usuarios->buscarPorEmail((string) $body['email'])) {
            return $this->json($response, ['error' => 'Ya existe un usuario con ese email'], 422);
        }

        $id = $this->usuarios->crear(
            (string) $body['nombre'],
            (string) $body['email'],
            password_hash((string) $body['password'], PASSWORD_DEFAULT),
            (string) $body['rol']
        );

        return $this->json($response, $this->usuarios->buscarPorId($id), 201);
    }

    private function json(Response $response, $data, int $status = 200): Response
    {
        if (is_array($data)) {
            unset($data['password_hash']);
        }
        $response->getBody()->write(json_encode($data));

        return $response->withHeader('Content-Type', 'application/json')->withStatus($status);
    }
}
