'use server';

import { revalidatePath } from 'next/cache';
import { API_BASE } from '../../lib/api';
import { getAuthHeaders } from '../../lib/auth-headers';

export async function addPantryItem(productId: number) {
  const res = await fetch(`${API_BASE}/api/pantry`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', ...(await getAuthHeaders()) },
    body: JSON.stringify({ productId }),
    cache: 'no-store',
  });

  if (!res.ok) {
    const text = await res.text();
    throw new Error(`Kunde inte lägga till i baslagret: ${text}`);
  }

  revalidatePath('/baslager');
}

export async function removePantryItem(id: number) {
  const res = await fetch(`${API_BASE}/api/pantry/${id}`, {
    method: 'DELETE',
    headers: { ...(await getAuthHeaders()) },
    cache: 'no-store',
  });

  if (!res.ok) {
    const text = await res.text();
    throw new Error(`Kunde inte ta bort från baslagret: ${text}`);
  }

  revalidatePath('/baslager');
}
