<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Response;

final class UploadController
{
    public function image(): void
    {
        Auth::requireRole(['admin', 'delegate']);
        if (empty($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
            Response::error('Imagen inválida', 422);
            return;
        }

        $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
        $mime = mime_content_type($_FILES['image']['tmp_name']);
        if (!isset($allowed[$mime])) {
            Response::error('Formato no permitido', 422);
            return;
        }

        $name = bin2hex(random_bytes(12)) . '.' . $allowed[$mime];
        $target = __DIR__ . '/../../public/uploads/' . $name;
        move_uploaded_file($_FILES['image']['tmp_name'], $target);
        Response::json(['path' => '/uploads/' . $name], 201);
    }
}
