/* Copyright (C) 2024 Manuel Bustillo*/

import { asArray, getCsrfToken, getSlug } from '@/app/lib/utils';
import { Captcha, StructuredErrors, User } from '@/app/lib/definitions';

export function login({ email, password, onLogin }: { email: string, password: string, onLogin: (user: User) => void }) {
  return fetch(`/api/${getSlug()}/users/sign_in`, {
    method: 'POST',
    body: JSON.stringify({ user: { email, password } }),
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': getCsrfToken(),
    }
  })
    .then((response) => response.json())
    .then((data: any) => {
      console.log(data);
      onLogin({
        id: data.id || '',
        email: data.email || '',
      });
    })
    .catch((error) => console.error(error));
}

export function logout({ onLogout }: { onLogout: () => void }) {
  fetch(`/api/${getSlug()}/users/sign_out`, {
    method: 'DELETE',
    headers: {
      'X-CSRF-TOKEN': getCsrfToken(),
    }
  }).then(onLogout)
    .catch((error) => console.error(error));
}

function flattenErrors(errors: StructuredErrors): string[] {
  if (errors instanceof Array) {
    return errors;
  }
  return Object.keys(errors).map((key) => {
    return `${key}: ${asArray(errors[key]).join(', ')}`;
  });
}

// At this moment we're making an initial request to get a valid CSRF token
export function retrieveCSRFToken() {
  return fetch(`/api/token`, {
    headers: {
      'Accept': 'application/json',
    }
  }).then((response) => { return null });
}

export function register({ slug, email, password, passwordConfirmation, captcha, onRegister, onError }: {
  slug: string,
  email: string,
  password: string,
  passwordConfirmation: string,
  captcha: Captcha,
  onRegister: () => void,
  onError: (errors: string[]) => void
}) {
  fetch(`/api/${slug}/users`, {
    method: 'POST',
    body: JSON.stringify(
      {
        user: { email, password, password_confirmation: passwordConfirmation },
        captcha: { id: captcha.id, answer: captcha.answer }
      }
    ),
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': getCsrfToken(),
    }
  }).then((response) => {
    if (response.ok) {
      response.json().then(onRegister);
    } else {
      response.json().then((data: any) => {
        onError(data.errors && flattenErrors(data.errors) || [data.error]);
      });
    }
  })
}