<?php

namespace App\Exceptions;

use App\Http\Responses\ApiResponse;
use App\Core\Response;

class Handler
{
    public static function render(\Throwable $e): Response
    {
        self::log($e);

        if ($e instanceof ValidationException) {
            return ApiResponse::error($e->getMessage(), 422, $e->details());
        }

        if ($e instanceof AuthException) {
            return ApiResponse::error($e->getMessage(), $e->status(), $e->details());
        }

        return ApiResponse::error('Server error', 500, [
            'exception' => (($_ENV['APP_DEBUG'] ?? 'false') === 'true') ? $e->getMessage() : null,
        ]);
    }

    private static function log(\Throwable $e): void
    {
        $dir = dirname(__DIR__, 2) . '/storage/logs';
        if (!is_dir($dir)) {
            @mkdir($dir, 0775, true);
        }

        @file_put_contents($dir . '/auth-service.log', sprintf(
            "[%s] %s: %s in %s:%d\n",
            date('c'),
            $e::class,
            $e->getMessage(),
            $e->getFile(),
            $e->getLine()
        ), FILE_APPEND);
    }
}
