/* Copyright (C) 2024 Manuel Bustillo*/

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

export function loadGuests(onLoad?: (guests: Guest[]) => void) {
  fetch(`/api/${getSlug()}/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/${getSlug()}/guests/${guest.id}`,
    {
      method: 'PUT',
      body: JSON.stringify({ guest: { name: guest.name, status: guest.status, group_id: guest.groupId } }),
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': getCsrfToken(),
      }
    })
    .catch((error) => console.error(error));
}

export function createGuest(guest: Guest, onCreate?: () => void) {
  fetch(`/api/${getSlug()}/guests`, {
    method: 'POST',
    body: JSON.stringify({ name: guest.name, group_id: guest.groupId, status: guest.status }),
    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/${getSlug()}/guests/${guest.id}`, {
    method: 'DELETE',
    headers: {
      'X-CSRF-TOKEN': getCsrfToken(),
    }
  })
    .then((response) => response.json())
    .then((data) => {
      onDestroy && onDestroy();
    })
    .catch((error) => console.error(error));
}