<?php

namespace AuthStack\UserDirectory\Exceptions;

use Illuminate\Http\JsonResponse;

class UserDirectoryException extends \Exception
{
    protected $msg;

    public function __construct($message, int $code = 0, $previous = null)
    {
        if(is_array($message))
        {
            parent::__construct(json_encode($message), $code, $previous);
        }
        else
        {
            parent::__construct($message, $code, $previous);
        }

        $this->msg = $message;
    }

    public function render(): JsonResponse
    {
        return response()->json($this->getErrorMessage(), $this->getHttpStatusCode());
    }

    protected function getHttpStatusCode(): int
    {
        if(empty($this->getCode()) || 0 === $this->getCode())
        {
            return 422;
        }

        return $this->getCode();
    }

    public function getErrorMessage(): array
    {
        if(is_array($this->msg))
        {
            return $this->msg;
        }
        else
        {
            return ['error' => [$this->msg]];
        }
    }
}