import api from './client'

export interface Material {
  id: string
  name: string
  description: string | null
  source: string
  schaeffler_code: number | null
  created_by_name: string | null
  aliases: string[]
  created_at: string
  updated_at: string
}

export interface MaterialAlias {
  id: string
  alias: string
  created_at: string
}

export async function listMaterials() {
  const res = await api.get<Material[]>('/materials')
  return res.data
}

export async function createMaterial(data: {
  name: string
  description?: string
  source?: string
  schaeffler_code?: number | null
}) {
  const res = await api.post<Material>('/materials', data)
  return res.data
}

export async function updateMaterial(id: string, data: { name?: string; description?: string }) {
  const res = await api.patch<Material>(`/materials/${id}`, data)
  return res.data
}

export async function deleteMaterial(id: string) {
  await api.delete(`/materials/${id}`)
}

export async function saveCadPartMaterials(
  orderId: string,
  itemId: string,
  parts: Array<{ part_name: string; material: string }>,
) {
  const res = await api.put(`/orders/${orderId}/items/${itemId}/cad-materials`, { parts })
  return res.data
}

export async function seedSchaefflerMaterials() {
  const res = await api.post<{ inserted: number; total: number }>('/materials/seed-schaeffler')
  return res.data
}

export async function getNextCode(typePrefix: string) {
  const res = await api.get<{ next_code: number; prefix: string; next_consecutive: number }>(
    `/materials/next-code`,
    { params: { type_prefix: typePrefix } },
  )
  return res.data
}

// --- Alias endpoints ---

export async function listAliases(materialId: string): Promise<MaterialAlias[]> {
  const res = await api.get<MaterialAlias[]>(`/materials/${materialId}/aliases`)
  return res.data
}

export async function addAlias(materialId: string, alias: string): Promise<MaterialAlias> {
  const res = await api.post<MaterialAlias>(`/materials/${materialId}/aliases`, { alias })
  return res.data
}

export async function deleteAlias(aliasId: string): Promise<void> {
  await api.delete(`/materials/aliases/${aliasId}`)
}

export async function seedAliases(): Promise<{ inserted: number; total: number }> {
  const res = await api.post<{ inserted: number; total: number }>('/materials/seed-aliases')
  return res.data
}
