<?php

namespace App\Libraries;

use CodeIgniter\HTTP\ResponseInterface;

class ResponseHelper
{
    public static function success(
        mixed $data = null,
        int $statusCode = 200,
        ?array $meta = null
    ): ResponseInterface {
        $payload = ['status' => 'success'];

        if ($data !== null) {
            $payload['data'] = $data;
        }

        if ($meta !== null) {
            $payload['meta'] = $meta;
        }

        return response()->setStatusCode($statusCode)
                         ->setContentType('application/json')
                         ->setJSON($payload);
    }

    public static function created(mixed $data = null): ResponseInterface
    {
        return self::success($data, 201);
    }

    public static function paginated(array $result): ResponseInterface
    {
        return self::success($result['data'], 200, $result['meta']);
    }

    public static function error(
        string $message,
        int $statusCode = 400,
        ?array $errors = null
    ): ResponseInterface {
        $payload = [
            'status'  => 'error',
            'message' => $message,
        ];

        if ($errors !== null) {
            $payload['errors'] = $errors;
        }

        return response()->setStatusCode($statusCode)
                         ->setContentType('application/json')
                         ->setJSON($payload);
    }

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

    public static function unauthorized(string $message = 'Unauthorized'): ResponseInterface
    {
        return self::error($message, 401);
    }

    public static function forbidden(string $message = 'Forbidden'): ResponseInterface
    {
        return self::error($message, 403);
    }

    public static function validationError(array $errors): ResponseInterface
    {
        return self::error('Validation failed', 422, $errors);
    }

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