import { apiClient } from './api-client';
import type { z } from 'zod/v4';
import type {
  ProductResponseSchema,
  ProductListResponseSchema,
  CreateProductInput,
  UpdateProductInput,
} from '@meshitrack/shared';

type ProductResponse = z.infer<typeof ProductResponseSchema>;
type ProductListResponse = z.infer<typeof ProductListResponseSchema>;

export interface ProductQuery {
  q?: string;
  category?: string;
  tags?: string;
  barcode?: string;
  cursor?: string;
  limit?: number;
}

export async function listProducts(
  householdId: string,
  query?: ProductQuery,
): Promise<ProductListResponse> {
  const params = new URLSearchParams();
  if (query?.q) params.set('q', query.q);
  if (query?.category) params.set('category', query.category);
  if (query?.tags) params.set('tags', query.tags);
  if (query?.barcode) params.set('barcode', query.barcode);
  if (query?.cursor) params.set('cursor', query.cursor);
  if (query?.limit) params.set('limit', String(query.limit));
  const qs = params.toString();
  return apiClient.get<ProductListResponse>(
    `/households/${householdId}/products${qs ? `?${qs}` : ''}`,
  );
}

export async function getProduct(householdId: string, id: string): Promise<ProductResponse> {
  return apiClient.get<ProductResponse>(`/households/${householdId}/products/${id}`);
}

export async function lookupBarcode(
  householdId: string,
  barcode: string,
): Promise<ProductResponse | { found: false }> {
  return apiClient.get<ProductResponse | { found: false }>(
    `/households/${householdId}/products/barcode/${barcode}`,
  );
}

export async function createProduct(
  householdId: string,
  data: CreateProductInput,
): Promise<ProductResponse> {
  return apiClient.post<ProductResponse>(`/households/${householdId}/products`, data);
}

export async function updateProduct(
  householdId: string,
  id: string,
  data: UpdateProductInput,
): Promise<ProductResponse> {
  return apiClient.patch<ProductResponse>(`/households/${householdId}/products/${id}`, data);
}

export async function deleteProduct(householdId: string, id: string): Promise<void> {
  return apiClient.delete(`/households/${householdId}/products/${id}`);
}

export async function smartAddProduct(
  householdId: string,
  text: string,
): Promise<{ available: false; message: string }> {
  return apiClient.post<{ available: false; message: string }>(
    `/households/${householdId}/products/smart-add`,
    { text },
  );
}

export async function importProducts(
  householdId: string,
  file: File,
): Promise<{
  imported: number;
  skippedDuplicates: number;
  errors: { row: number; message: string }[];
}> {
  const formData = new FormData();
  formData.append('file', file);
  const baseUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api/v1';
  const res = await fetch(`${baseUrl}/households/${householdId}/products/import`, {
    method: 'POST',
    body: formData,
  });
  if (!res.ok) {
    let message: string;
    try {
      const body = await res.json();
      message = body.message || `Import failed: ${res.status}`;
    } catch {
      message = `Import failed: ${res.status} ${res.statusText}`;
    }
    throw new Error(message);
  }
  return res.json();
}
