import { CreateUserRequest } from "../src/shared/services/createStripeUser";

interface CreatePetisgoUser extends Partial<CreateUserRequest> {
  username?: string;
  birthdate?: string;
}

export interface CreateAppUserResponse {
  acceptedlegalversion: number;
  activesessions: string[];
  appname: string;
  birthdate: string;
  bookmarks: string[];
  createdAt: string;
  email: string;
  favorites: string[];
  firstname: string;
  groups: string[];
  id: string;
  interests: string[];
  language: string;
  lastname: string;
  ratings: string[];
  role: string;
  suggestions: string[];
  updatedAt: string;
  username: string;
}

export async function createAppUser(
  body?: CreatePetisgoUser
): Promise<CreateAppUserResponse> {
  const endpoint = "https://petisgo.tiivii.com/v1/iden/users/andromeda/user/";

  const response = await fetch(endpoint, {
    body: body ? JSON.stringify(body) : undefined,
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  });

  if (!response.ok || response.status.toString()[0] !== "2") {
    throw new Error(
      `API call failed to ${endpoint} (${response.status}): ${JSON.stringify(
        await response.json()
      )}`
    );
  }

  const resp = (await response.json()) as any;

  if (resp.error_error) {
    let errorMessage = `API Failed with error: ${JSON.stringify(resp)}`;

    try {
      errorMessage = JSON.parse(resp.error_error.http_body).message;
    } catch (error) {}

    throw new Error(errorMessage);
  }

  return resp;
}
