'use server';

import { revalidatePath } from 'next/cache';

/**
 * Example server action for creating an item.
 * Server actions run on the server and can be called from client components.
 *
 * @example
 * // In a client component:
 * import { createItem } from '@/actions/example';
 *
 * <form action={createItem}>
 *   <input name="name" />
 *   <button type="submit">Create</button>
 * </form>
 */
export async function createItem(formData: FormData) {
  const name = formData.get('name') as string;

  if (!name || name.trim().length === 0) {
    return { success: false, error: 'Name is required' };
  }

  // Example: Call your API service
  // const response = await fetch(`${process.env.API_URL}/api/items`, {
  //   method: 'POST',
  //   headers: {
  //     'Content-Type': 'application/json',
  //     'Authorization': `Bearer ${getToken()}`,
  //   },
  //   body: JSON.stringify({ name }),
  // });

  // Simulate API call
  await new Promise((resolve) => setTimeout(resolve, 500));

  // Revalidate the page data
  revalidatePath('/dashboard');

  return { success: true, data: { id: crypto.randomUUID(), name } };
}

/**
 * Example server action for deleting an item.
 */
export async function deleteItem(id: string) {
  if (!id) {
    return { success: false, error: 'ID is required' };
  }

  // Example: Call your API service
  // await fetch(`${process.env.API_URL}/api/items/${id}`, {
  //   method: 'DELETE',
  // });

  // Simulate API call
  await new Promise((resolve) => setTimeout(resolve, 300));

  // Revalidate the page data
  revalidatePath('/dashboard');

  return { success: true };
}

/**
 * Example server action for fetching data.
 * This can be used for server-side data fetching in Server Components.
 */
export async function getItems() {
  // Example: Fetch from your API
  // const response = await fetch(`${process.env.API_URL}/api/items`, {
  //   next: { revalidate: 60 }, // Cache for 60 seconds
  // });
  // return response.json();

  // Simulate API response
  return {
    items: [
      { id: '1', name: 'Item 1', createdAt: new Date().toISOString() },
      { id: '2', name: 'Item 2', createdAt: new Date().toISOString() },
    ],
    total: 2,
  };
}
