<?php

namespace Khofmann\ApiError;

use Exception;

/**
 * Facade for common API errors
 */
class ApiError extends Exception
{
  private function __construct($message = "", $code = 0)
  {
    parent::__construct($message, $code);
  }

  /**
   * Error for missing fields
   *
   * @param array $fields Array of strings denoting which fields were missing
   */
  public static function missingField(array $fields): ApiError
  {
    return new ApiError(json_encode([
      "code" => "MissingField",
      "fields" => $fields,
    ]), 400);
  }

  /**
   * Error for duplicates
   *
   * @param string entity Entity for which a duplicate exists
   */
  public static function duplicate(string $entity): ApiError
  {
    return new ApiError(json_encode([
      "code" => "Duplicate",
      "entity" => $entity,
    ]), 400);
  }

  /**
   * Error for missing permissions
   *
   * @param string message Message specifics
   */
  public static function notAllowed(string $message)
  {
    return new ApiError(json_encode([
      "code" => "NotAllowed",
      "message" => $message,
    ]), 401);
  }

  /**
   * Error for missing authentication
   *
   * @param string $message Message specifics
   */
  public static function unauthorized(string $message)
  {
    return new ApiError(json_encode([
      "code" => "Unauthorized",
      "message" => $message,
    ]), 401);
  }

  /**
   * Error for not found
   *
   * @param string entity Entity for which a duplicate exists
   */
  public static function notFound(string $entity)
  {
    return new ApiError(json_encode([
      "code" => "NotFound",
      "entity" => $entity,
    ]), 404);
  }

  /**
   * Generic error
   *
   * @param string message Message specifics
   */
  public static function failed(string $message)
  {
    return new ApiError(json_encode([
      "code" => "Failed",
      "message" => $message,
    ]), 500);
  }

  /**
   * Error for missing fields
   *
   * @param array $fields Array of strings denoting which fields failed
   * @param array $fields Array of strings denoting why the fields failed
   */
  public static function failedUpdate(array $fields, array $reasons)
  {
    return new ApiError(json_encode([
      "code" => "FailedUpdate",
      "fields" => $fields,
      "reasons" => $reasons,
    ]), 500);
  }
}
