export interface StaffMember {
  id: string;
  restaurantId: string;
  branchId?: string;
  name: string;
  email: string;
  phone?: string;
  role: string;
  isActive: boolean;
  hireDate?: string;
  salary?: number;
  createdAt: string;
  updatedAt: string;
}

export interface StaffListResponse {
  staff: StaffMember[];
  total: number;
  page: number;
  limit: number;
  pages: number;
}

async function apiFetch<T>(url: string, options?: RequestInit): Promise<T> {
  const res = await fetch(url, { credentials: 'include', ...options });
  const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
  if (!res.ok) throw new Error((json.error as string) || `Request failed: ${res.status}`);
  return json as T;
}

export async function listStaff(params: Record<string, string> = {}): Promise<StaffListResponse> {
  const qs = new URLSearchParams(params).toString();
  return apiFetch<StaffListResponse>(`/api/staff${qs ? '?' + qs : ''}`);
}

export async function getStaff(id: string): Promise<{ staff: StaffMember }> {
  return apiFetch<{ staff: StaffMember }>(`/api/staff/${id}`);
}

export async function createStaff(body: Record<string, unknown>): Promise<{ staff: StaffMember }> {
  return apiFetch<{ staff: StaffMember }>('/api/staff', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
}

export async function updateStaff(id: string, body: Record<string, unknown>): Promise<{ staff: StaffMember }> {
  return apiFetch<{ staff: StaffMember }>(`/api/staff/${id}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
}

export async function deleteStaff(id: string): Promise<{ success: boolean }> {
  return apiFetch<{ success: boolean }>(`/api/staff/${id}`, { method: 'DELETE' });
}
