<?php

namespace Modules\Service\Responses;

use Throwable;
use Illuminate\Http\Response;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Http\Exceptions\HttpResponseException;

class ApiErrorResponse implements Responsable
{
    public function __construct(
        private readonly mixed $message,
        private readonly ?string $help = null,
        private readonly ?Throwable $exception = null,
        private readonly int $code = Response::HTTP_INTERNAL_SERVER_ERROR,
        private readonly array $headers = []
    ) {
    }

    /**
     * @param $request
     * @return \Symfony\Component\HttpFoundation\Response|void
     */
    public function toResponse($request)
    {
        $response = [
            'status'  => $this->code,
            'message' => $this->message,
            'help'    => $this->help,
            'data'    => null,
        ];

        if (! is_null($this->exception) && config('app.debug')) {
            $response['debug'] = [
                'message' => $this->exception->getMessage(),
                'file'    => $this->exception->getFile(),
                'line'    => $this->exception->getLine(),
                'trace'   => $this->exception->getTraceAsString(),
            ];
        }

        throw new HttpResponseException(response()->json(['errors' => $this->message], $this->code,$this->headers));
    }
}
