<?php

use MintyPHP\Http\ApiAuth;
use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;
use MintyPHP\Service\User\UserServicesFactory;

define('MINTY_ALLOW_OUTPUT', true);

ApiBootstrap::init();

$request = requestInput();
$method = $request->method();
$userServicesFactory = app(UserServicesFactory::class);
$userAvatarService = $userServicesFactory->createUserAvatarService();
$user = ApiAuth::user();
$uuid = (string) ($user['uuid'] ?? '');

if ($method === 'GET') {
    $size = $request->hasQuery('size') ? $request->queryInt('size') : null;

    $path = $userAvatarService->findAvatarPath($uuid, $size);
    if (!$path || !is_file($path)) {
        http_response_code(404);
        header('Content-Type: application/json');
        echo json_encode(['error' => 'not_found']);
        return;
    }

    $mime = $userAvatarService->detectMime($path);
    header('Content-Type: ' . $mime);
    header('X-Content-Type-Options: nosniff');
    header('Content-Security-Policy: sandbox');
    header('Cache-Control: private, max-age=300');
    header('Content-Length: ' . filesize($path));
    readfile($path);
    return;
}

if ($method === 'POST') {
    ApiResponse::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_API_ME_SELF_UPDATE);

    $result = $userAvatarService->saveUpload($uuid, $request->file('avatar', []));
    if (!($result['ok'] ?? false)) {
        $error = $result['error'] ?? 'upload_failed';
        ApiResponse::error($error, 422);
    }

    ApiResponse::created(['data' => ['message' => 'avatar_updated']]);
}

if ($method === 'DELETE') {
    ApiResponse::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_API_ME_SELF_UPDATE);

    $userAvatarService->delete($uuid);
    ApiResponse::noContent();
}

ApiResponse::methodNotAllowed();
