<?php

declare(strict_types=1);

namespace App\Helpers;

use App\Core\Response;

/**
 * AjaxResponse
 *
 * Every AJAX/API endpoint in the app replies with the same envelope
 * shape, so the frontend's vanilla-JS fetch() calls can handle success
 * and failure generically instead of guessing each controller's format:
 *
 *   { "success": true,  "data": {...}, "message": "..." }
 *   { "success": false, "message": "...", "errors": {...} }
 */
final class AjaxResponse
{
    public static function success(mixed $data = null, string $message = '', int $status = 200): Response
    {
        return Response::json([
            'success' => true,
            'message' => $message,
            'data' => $data,
        ], $status);
    }

    public static function created(mixed $data = null, string $message = 'Created successfully.'): Response
    {
        return self::success($data, $message, 201);
    }

    public static function error(string $message = 'Something went wrong.', int $status = 400, array $errors = []): Response
    {
        return Response::json([
            'success' => false,
            'message' => $message,
            'errors' => $errors,
        ], $status);
    }

    public static function validationError(array $errors, string $message = 'The given data was invalid.'): Response
    {
        return self::error($message, 422, $errors);
    }

    public static function unauthorized(string $message = 'Authentication required.'): Response
    {
        return self::error($message, 401);
    }

    public static function forbidden(string $message = 'You do not have permission to do that.'): Response
    {
        return self::error($message, 403);
    }

    public static function notFound(string $message = 'Resource not found.'): Response
    {
        return self::error($message, 404);
    }

    public static function tooManyRequests(string $message = 'Too many attempts. Please try again shortly.'): Response
    {
        return self::error($message, 429);
    }

    public static function serverError(string $message = 'An unexpected error occurred.'): Response
    {
        return self::error($message, 500);
    }
}
