<?php

namespace App\Services;

use App\Exceptions\ForbiddenException;
use App\Exceptions\UnauthorizedException;
use App\Exceptions\UnprocessableException;
use App\Utils\FileUtil;
use Illuminate\Support\Facades\Log;
use Throwable;

class ResponseService
{
    public static $errorCodes = [
        1000 => 'NO_PAID_PLAN',
    ];

    public static function ok(array|object $data)
    {
        return response()->json($data, 200);
    }

    public static function bad(string $message)
    {
        return response()->json(compact('message'), 400);
    }

    public static function unauthorized(string $message = null)
    {
        $message = $message ? $message : 'Unauthorized access. Please sign in';
        return response()->json(compact('message'), 401);
    }

    public static function forbidden(string $message, int $code = null)
    {
        $code = self::$errorCodes[$code];
        return response()->json(compact('message', 'code'), 403);
    }

    public static function unprocessable(string $message)
    {
        return response()->json(compact('message'), 422);
    }

    public static function serverError()
    {
        $message = 'Unable to process your request';
        return response()->json(compact('message'), 500);
    }

    public static function storage($path)
    {
        $filePath = storage_path("/app/public/$path");
        $mimeType = FileUtil::mimeTypeFromPath($filePath);
        return response()->file($filePath, [
            'Content-Type' => $mimeType,
        ]);
    }

    public static function resource($path)
    {
        $filePath = resource_path($path);
        $mimeType = FileUtil::mimeTypeFromPath($filePath);
        return response()->file($filePath, [
            'Content-Type' => $mimeType,
        ]);
    }

    public static function handleError(Throwable $error)
    {
        $message = $error->getMessage();
        $code = $error->getCode();
        if ($error instanceof UnprocessableException) {
            return self::unprocessable($message);
        } else if ($error instanceof UnauthorizedException) {
            return self::unauthorized($message);
        } else if ($error instanceof ForbiddenException) {
            return self::forbidden($message, $code);
        } else {
            Log::error($error);
            return self::serverError();
        }
    }
}
