<?php

namespace Khofmann\ApiError;

use Exception;

class ApiError extends Exception
{
  private function __construct($message = "", $code = 0)
  {
    parent::__construct($message, $code);
  }

  public static function missingField(array $fields): ApiError
  {
    return new ApiError(json_encode([
      "code" => "MissingField",
      "fields" => $fields,
    ]), 400);
  }

  public static function duplicate(string $entity): ApiError
  {
    return new ApiError(json_encode([
      "code" => "Duplicate",
      "entity" => $entity,
    ]), 400);
  }

  public static function unauthorized(string $message)
  {
    return new ApiError(json_encode([
      "code" => "Unauthorized",
      "message" => $message,
    ]), 401);
  }

  public static function notFound(string $entity)
  {
    return new ApiError(json_encode([
      "code" => "NotFound",
      "entity" => $entity,
    ]), 404);
  }

  public static function failed(string $message)
  {
    return new ApiError(json_encode([
      "code" => "Failed",
      "message" => $message,
    ]), 500);
  }

  public static function failedUpdate(array $fields, array $reasons)
  {
    return new ApiError(json_encode([
      "code" => "FailedUpdate",
      "fields" => $fields,
      "reasons" => $reasons,
    ]), 500);
  }
}
