import {
  CreateStandardInput,
  CreateStandardOutput,
  GetStandardOutput,
  GetStandardsOutput,
  PatchStandardInput,
  PatchStandardOutput,
} from './types'

const BASE_URL = '/api'

// Получить все эталоны
export const getStandards = async (): Promise<GetStandardsOutput> => {
  console.log('getStandards', BASE_URL)
  const response = await fetch(`${BASE_URL}/standards/`)
  if (!response.ok) {
    throw new Error('Failed to fetch standards')
  }
  return response.json()
}

// Получить один эталон
export const getStandard = async (
  standardId: string
): Promise<GetStandardOutput> => {
  const response = await fetch(`${BASE_URL}/standards/${standardId}`)
  if (!response.ok) {
    throw new Error('Failed to fetch standard')
  }
  return response.json()
}

// Создать эталон
export const createStandard = async (
  input: CreateStandardInput
): Promise<CreateStandardOutput> => {
  const response = await fetch(`${BASE_URL}/standards/`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(input),
  })
  if (!response.ok) {
    throw new Error('Failed to create standard')
  }
  return response.json()
}

// Обновить эталон
export const patchStandard = async (
  standardId: string,
  input: PatchStandardInput
): Promise<PatchStandardOutput> => {
  const response = await fetch(`${BASE_URL}/standards/${standardId}`, {
    method: 'PATCH',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(input),
  })
  if (!response.ok) {
    throw new Error('Failed to update standard')
  }
  return response.json()
}

// Удалить эталон
export const deleteStandard = async (
  standardId: string
): Promise<{ [key: string]: string }> => {
  const response = await fetch(`${BASE_URL}/standards/${standardId}`, {
    method: 'DELETE',
  })
  if (!response.ok) {
    throw new Error('Failed to delete standard')
  }
  return response.json()
}
