import api from './client';

export interface RenderTemplate {
  id: string;
  name: string;
  category_key: string | null;
  output_type_id: string | null;
  output_type_name: string | null;
  blend_file_path: string;
  original_filename: string;
  target_collection: string;
  material_replace_enabled: boolean;
  lighting_only: boolean;
  shadow_catcher_enabled: boolean;
  camera_orbit: boolean;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

export interface MaterialLibraryInfo {
  exists: boolean;
  filename: string | null;
  size_bytes: number | null;
  path: string | null;
}

export async function listRenderTemplates(): Promise<RenderTemplate[]> {
  const { data } = await api.get('/render-templates');
  return data;
}

export async function createRenderTemplate(formData: FormData): Promise<RenderTemplate> {
  const { data } = await api.post('/render-templates', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
  });
  return data;
}

export async function updateRenderTemplate(
  id: string,
  updates: Partial<Pick<RenderTemplate, 'name' | 'category_key' | 'output_type_id' | 'target_collection' | 'material_replace_enabled' | 'lighting_only' | 'shadow_catcher_enabled' | 'camera_orbit' | 'is_active'>>,
): Promise<RenderTemplate> {
  const { data } = await api.patch(`/render-templates/${id}`, updates);
  return data;
}

export async function deleteRenderTemplate(id: string): Promise<void> {
  await api.delete(`/render-templates/${id}`);
}

export async function reuploadBlendFile(id: string, file: File): Promise<RenderTemplate> {
  const fd = new FormData();
  fd.append('file', file);
  const { data } = await api.post(`/render-templates/${id}/upload`, fd, {
    headers: { 'Content-Type': 'multipart/form-data' },
  });
  return data;
}

export async function uploadMaterialLibrary(file: File): Promise<MaterialLibraryInfo> {
  const fd = new FormData();
  fd.append('file', file);
  const { data } = await api.post('/admin/settings/material-library', fd, {
    headers: { 'Content-Type': 'multipart/form-data' },
  });
  return data;
}

export async function getMaterialLibraryInfo(): Promise<MaterialLibraryInfo> {
  const { data } = await api.get('/admin/settings/material-library');
  return data;
}

export async function deleteMaterialLibrary(): Promise<void> {
  await api.delete('/admin/settings/material-library');
}
