import { NextApiResponse } from "next";

export type ApiResponse = ApiSuccessResponse | ApiErrorResponse;

interface ApiSuccessResponse<T = { [key: string]: unknown }> {
  data: T;
}

interface ApiErrorResponse {
  code:
    | "not_found"
    | "gone"
    | "bad_request"
    | "internal_server_error"
    | "unauthorized"
    | "method_not_allowed"
    | "not_authenticated"
    | "forbidden"
    | "too_many_requests"
    | "conflict"
    | "payload_too_large"
    | "service_unavailable"
    | "workspace_survey_limit_reached";
  message: string;
  details: {
    [key: string]: string | string[] | number | number[] | boolean | boolean[];
  };
}

export type CustomNextApiResponse = NextApiResponse<ApiResponse>;

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type, Authorization",
};

const goneResponse = (
  message: string,
  details?: { [key: string]: string },
  cors: boolean = false,
  cache: string = "private, no-store"
) => {
  const headers = {
    ...(cors && corsHeaders),
    "Cache-Control": cache,
  };

  return Response.json(
    {
      code: "gone",
      message,
      details: details || {},
    },
    {
      status: 410,
      headers,
    }
  );
};

const badRequestResponse = (
  message: string,
  details?: { [key: string]: string },
  cors: boolean = false,
  cache: string = "private, no-store"
) => {
  const headers = {
    ...(cors && corsHeaders),
    "Cache-Control": cache,
  };

  return Response.json(
    {
      code: "bad_request",
      message,
      details: details || {},
    },
    {
      status: 400,
      headers,
    }
  );
};

const payloadTooLargeResponse = (
  message: string = "Payload Too Large",
  details: ApiErrorResponse["details"] = {},
  cors: boolean = false,
  cache: string = "private, no-store"
) => {
  const headers = {
    ...(cors && corsHeaders),
    "Cache-Control": cache,
  };

  return Response.json(
    {
      code: "payload_too_large",
      message,
      details,
    },
    {
      status: 413,
      headers,
    }
  );
};

const methodNotAllowedResponse = (
  res: CustomNextApiResponse,
  allowedMethods: string[],
  cors: boolean = false,
  cache: string = "private, no-store"
) => {
  const headers = {
    ...(cors && corsHeaders),
    "Cache-Control": cache,
  };

  return Response.json(
    {
      code: "method_not_allowed",
      message: `The HTTP ${res.req?.method} method is not supported by this route.`,
      details: {
        allowed_methods: allowedMethods,
      },
    },
    {
      status: 405,
      headers,
    }
  );
};

const notFoundResponse = (
  resourceType: string,
  resourceId: string | null,
  cors: boolean = false,
  cache: string = "private, no-store"
) => {
  const headers = {
    ...(cors && corsHeaders),
    "Cache-Control": cache,
  };

  return Response.json(
    {
      code: "not_found",
      message: `${resourceType} not found`,
      details: {
        resource_id: resourceId,
        resource_type: resourceType,
      },
    },
    {
      status: 404,
      headers,
    }
  );
};

const notAuthenticatedResponse = (cors: boolean = false, cache: string = "private, no-store") => {
  const headers = {
    ...(cors && corsHeaders),
    "Cache-Control": cache,
  };

  return Response.json(
    {
      code: "not_authenticated",
      message: "Not authenticated",
      details: {
        "x-Api-Key": "Header not provided or API Key invalid",
      },
    },
    {
      status: 401,
      headers,
    }
  );
};

const unauthorizedResponse = (cors: boolean = false, cache: string = "private, no-store") => {
  const headers = {
    ...(cors && corsHeaders),
    "Cache-Control": cache,
  };

  return Response.json(
    {
      code: "unauthorized",
      message: "You are not authorized to access this resource",
      details: {},
    },
    {
      status: 401,
      headers,
    }
  );
};

const forbiddenResponse = (
  message: string,
  cors: boolean = false,
  details: ApiErrorResponse["details"] = {},
  cache: string = "private, no-store"
) => {
  const headers = {
    ...(cors && corsHeaders),
    "Cache-Control": cache,
  };

  return Response.json(
    {
      code: "forbidden",
      message,
      details,
    },
    {
      status: 403,
      headers,
    }
  );
};

const successResponse = (data: unknown, cors: boolean = false, cache: string = "private, no-store") => {
  const headers = {
    ...(cors && corsHeaders),
    "Cache-Control": cache,
  };

  return Response.json(
    {
      data,
    },
    {
      status: 200,
      headers,
    }
  );
};

/** 204 with no body, for endpoints that tell the caller nothing (the creative events beacon). */
const noContentResponse = (cors: boolean = false, cache: string = "private, no-store") =>
  new Response(null, {
    status: 204,
    headers: {
      ...(cors && corsHeaders),
      "Cache-Control": cache,
    },
  });

const internalServerErrorResponse = (
  message: string,
  cors: boolean = false,
  details: ApiErrorResponse["details"] = {},
  cache: string = "private, no-store"
) => {
  const headers = {
    ...(cors && corsHeaders),
    "Cache-Control": cache,
  };

  return Response.json(
    {
      code: "internal_server_error",
      message,
      details,
    },
    {
      status: 500,
      headers,
    }
  );
};

const conflictResponse = (
  message: string,
  details?: { [key: string]: string },
  cors: boolean = false,
  cache: string = "private, no-store"
) => {
  const headers = {
    ...(cors && corsHeaders),
    "Cache-Control": cache,
  };

  return Response.json(
    {
      code: "conflict",
      message,
      details: details || {},
    },
    {
      status: 409,
      headers,
    }
  );
};

/** ENG-3282: the workspace already holds its maximum number of surveys. */
const workspaceSurveyLimitResponse = (limit: number, count: number, cache: string = "private, no-store") =>
  Response.json(
    {
      code: "workspace_survey_limit_reached",
      message: "This workspace has reached its survey limit",
      details: { count, limit },
    },
    { status: 422, headers: { "Cache-Control": cache } }
  );

const tooManyRequestsResponse = (
  message: string,
  cors: boolean = false,
  cache: string = "private, no-store"
) => {
  const headers = {
    ...(cors && corsHeaders),
    "Cache-Control": cache,
  };

  return Response.json(
    {
      code: "too_many_requests",
      message,
      details: {},
    },
    {
      status: 429,
      headers,
    }
  );
};

/** The server cannot take the request right now; `retryAfterSeconds` tells the caller when to try again. */
const serviceUnavailableResponse = (message: string, retryAfterSeconds?: number) =>
  Response.json(
    {
      code: "service_unavailable",
      message,
      details: {},
    },
    {
      status: 503,
      headers: {
        "Cache-Control": "private, no-store",
        ...(retryAfterSeconds === undefined ? {} : { "Retry-After": String(retryAfterSeconds) }),
      },
    }
  );

export const responses = {
  goneResponse,
  badRequestResponse,
  internalServerErrorResponse,
  methodNotAllowedResponse,
  notAuthenticatedResponse,
  unauthorizedResponse,
  notFoundResponse,
  successResponse,
  noContentResponse,
  payloadTooLargeResponse,
  tooManyRequestsResponse,
  serviceUnavailableResponse,
  forbiddenResponse,
  conflictResponse,
  workspaceSurveyLimitResponse,
};
