<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Exception\Handler;

use App\Constants\HttpEnumCode;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Snowflake\IdGeneratorInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Hyperf\Di\Annotation\Inject;
use Throwable;

class AppExceptionHandler extends ExceptionHandler
{
    #[Inject]
    protected StdoutLoggerInterface $logger;

    protected string $environment;

    #[Inject]
    protected ContainerInterface $container;

    public function __construct(StdoutLoggerInterface $logger)
    {
        $this->logger = $logger;
        $this->environment = env("APP_ENV", 'prod');
    }

    public function handle(Throwable $throwable, ResponseInterface $response): ResponseInterface
    {
        try {
            if ($this->environment != "dev"){
                // 生产环境 固定返回服务器错误
                $message = HttpEnumCode::getMessage(HttpEnumCode::SERVER_ERROR);
            }else{
                $message = $throwable->getMessage();
            }

            $generator = $this->container->get(IdGeneratorInterface::class);
        } catch (NotFoundExceptionInterface|ContainerExceptionInterface $e) {
            $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
            $this->logger->error($throwable->getTraceAsString());
            return $response->withHeader('Server', 'gdxz')->withStatus(500)->withBody(new SwooleStream('服务器错误'));
        }

        $id = $generator->generate();

        $data = json_encode([
            'data' => $id,
            'code' => HttpEnumCode::SERVER_ERROR,
            'message' => $message,
        ], JSON_UNESCAPED_UNICODE);

        $this->logger->error($id . "-start");
        $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
        $this->logger->error($throwable->getTraceAsString());
        $this->logger->error($id . "-end");

        return $response->withStatus(500)->withHeader('content-type', 'application/json; charset=utf-8')->withBody(new SwooleStream($data));
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
