/* Copyright (C) 2024 Manuel Bustillo*/

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

export function loadGuests(onLoad?: (guests: Guest[]) => void) {
  fetch("/api/default/guests")
    .then((response) => response.json())
    .then((data) => {
      onLoad && onLoad(data.map((record: any) => {
        return ({
          id: record.id,
          name: record.name,
          status: record.status,
          group_name: record.group.name,
          groupId: record.group.id,
        });
      }));
    }, (error) => {
      return [];
    });
};

export function updateGuest(guest: Guest) {
  return fetch(`/api/default/guests/${guest.id}`,
    {
      method: 'PUT',
      body: JSON.stringify({ guest: { name: guest.name, status: guest.status } }),
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': getCsrfToken(),
      }
    })
    .catch((error) => console.error(error));
}

export function createGuest(name: string, group_id: string, onCreate?: () => void) {
  fetch("/api/default/guests", {
    method: 'POST',
    body: JSON.stringify({ name: name, group_id: group_id }),
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': getCsrfToken(),
    }
  })
    .then((response) => response.json())
    .then((data) => {
      onCreate && onCreate();
    })
    .catch((error) => console.error(error));
}

export function destroyGuest(guest: Guest, onDestroy?: () => void) {
  fetch(`/api/default/guests/${guest.id}`, {
    method: 'DELETE',
    headers: {
      'X-CSRF-TOKEN': getCsrfToken(),
    }
  })
    .then((response) => response.json())
    .then((data) => {
      onDestroy && onDestroy();
    })
    .catch((error) => console.error(error));
}