import api from './client'

export interface RenderPosition {
  id: string
  product_id: string
  name: string
  rotation_x: number
  rotation_y: number
  rotation_z: number
  is_default: boolean
  sort_order: number
  created_at: string
}

export interface ComponentData {
  part_name: string | null
  material: string | null
  component_type: string | null
  column_index: number
}

export interface CadPartMaterial {
  part_name: string
  material: string
}

export interface CadFileMeshAttributes {
  volume_mm3?: number
  surface_area_mm2?: number
  bbox?: { x?: number; y?: number; z?: number }
  suggested_smooth_angle?: number
  [key: string]: unknown
}

export interface Product {
  id: string
  pim_id: string
  name: string | null
  category_key: string | null
  ebene1: string | null
  ebene2: string | null
  baureihe: string | null
  produkt_baureihe: string | null
  lagertyp: string | null
  name_cad_modell: string | null
  gewuenschte_bildnummer: string | null
  medias_rendering: boolean | null
  components: ComponentData[]
  cad_part_materials: CadPartMaterial[]
  cad_file_id: string | null
  cad_file?: {
    id: string
    mesh_attributes?: CadFileMeshAttributes
  } | null
  thumbnail_url: string | null
  render_image_url: string | null
  processing_status: string | null
  stl_cached: string[]
  cad_parsed_objects: string[] | null
  cad_mesh_attributes?: {
    dimensions_mm?: { x: number; y: number; z: number }
    bbox_center_mm?: { x: number; y: number; z: number }
    suggested_smooth_angle?: number
    has_mechanical_edges?: boolean
    sharp_edge_midpoints?: number[][]
  } | null
  arbeitspaket: string | null
  notes: string | null
  is_active: boolean
  source_excel: string | null
  render_positions: RenderPosition[]
  created_at: string
  updated_at: string
}

export interface ProductListParams {
  q?: string
  category_key?: string
  has_cad?: boolean
  ready_only?: boolean
  materials_filter?: string   // "complete" | "incomplete" | ""
  skip?: number
  limit?: number
}

export async function listProducts(params?: ProductListParams): Promise<Product[]> {
  const res = await api.get<Product[]>('/products', { params })
  return res.data
}

export async function getProduct(id: string): Promise<Product> {
  const res = await api.get<Product>(`/products/${id}`)
  return res.data
}

export async function createProduct(data: Partial<Product>): Promise<Product> {
  const res = await api.post<Product>('/products', data)
  return res.data
}

export async function updateProduct(id: string, data: Partial<Product>): Promise<Product> {
  const res = await api.patch<Product>(`/products/${id}`, data)
  return res.data
}

export async function deleteProduct(id: string, hard = false): Promise<void> {
  await api.delete(`/products/${id}`, { params: hard ? { hard: true } : undefined })
}

export async function uploadProductCad(id: string, file: File) {
  const form = new FormData()
  form.append('file', file)
  const res = await api.post(`/products/${id}/cad`, form, {
    headers: { 'Content-Type': 'multipart/form-data' },
  })
  return res.data
}

export async function saveProductCadMaterials(id: string, parts: CadPartMaterial[]): Promise<Product> {
  const res = await api.post<Product>(`/products/${id}/cad-materials`, { parts })
  return res.data
}

export async function regenerateProduct(id: string) {
  const res = await api.post(`/products/${id}/regenerate`)
  return res.data
}

export async function reprocessProduct(id: string) {
  const res = await api.post(`/products/${id}/reprocess`)
  return res.data
}

export async function reassignMaterialsFromExcel(id: string): Promise<Product> {
  const res = await api.post<Product>(`/products/${id}/reassign-materials-from-excel`)
  return res.data
}

export interface ProductRender {
  order_line_id: string
  order_number: string | null
  output_type_name: string | null
  render_url: string
  is_video: boolean
  render_backend: string | null
  completed_at: string | null
}

export async function getProductRenders(id: string): Promise<ProductRender[]> {
  const res = await api.get<ProductRender[]>(`/products/${id}/renders`)
  return res.data
}

export async function deleteProductRender(productId: string, orderLineId: string): Promise<void> {
  await api.delete(`/products/${productId}/renders/${orderLineId}`)
}

export async function downloadProductRenders(
  productId: string,
  orderLineIds: string[],
  filename?: string,
): Promise<void> {
  const res = await api.post<Blob>(
    `/products/${productId}/download-renders`,
    { order_line_ids: orderLineIds },
    { responseType: 'blob' },
  )
  const url = URL.createObjectURL(res.data)
  const a = document.createElement('a')
  a.href = url
  a.download = filename ?? 'renders.zip'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

export async function getProductOrders(id: string) {
  const res = await api.get(`/products/${id}/orders`)
  return res.data
}

export async function listRenderPositions(productId: string): Promise<RenderPosition[]> {
  const res = await api.get<RenderPosition[]>(`/products/${productId}/render-positions`)
  return res.data
}

export async function createRenderPosition(
  productId: string,
  data: { name: string; rotation_x: number; rotation_y: number; rotation_z: number; is_default?: boolean; sort_order?: number },
): Promise<RenderPosition> {
  const res = await api.post<RenderPosition>(`/products/${productId}/render-positions`, data)
  return res.data
}

export async function updateRenderPosition(
  productId: string,
  posId: string,
  data: Partial<{ name: string; rotation_x: number; rotation_y: number; rotation_z: number; is_default: boolean; sort_order: number }>,
): Promise<RenderPosition> {
  const res = await api.patch<RenderPosition>(`/products/${productId}/render-positions/${posId}`, data)
  return res.data
}

export async function deleteRenderPosition(productId: string, posId: string): Promise<void> {
  await api.delete(`/products/${productId}/render-positions/${posId}`)
}

