/* Copyright (C) 2024 Manuel Bustillo*/

import { getCsrfToken } from '@/app/lib/utils';
import { User } from '@/app/lib/definitions';

export function login({ email, password, onLogin }: { email: string, password: string, onLogin: (user: User) => void }) {
  console.log(email, password);
  return fetch("/api/default/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/default/users/sign_out", {
    method: 'DELETE',
    headers: {
      'X-CSRF-TOKEN': getCsrfToken(),
    }
  }).then(onLogout)
    .catch((error) => console.error(error));
}
