import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'
import type {
  CreateWebsiteCategoryGroupPayload,
  UpdateWebsiteCategoryGroupPayload,
  WebsiteCategoryGroup,
  WebsiteCategoryGroupsListResponse,
} from '../types/websiteCategoryGroup'

function businessPath(suffix = '') {
  const businessId = getActiveBusinessId()
  if (!businessId) {
    throw new Error('No active business selected. Please sign in again.')
  }
  return `/businesses/${businessId}/website/category-groups${suffix}`
}

export async function listWebsiteCategoryGroups(page = 1, pageSize = 50, signal?: AbortSignal) {
  return apiRequest<WebsiteCategoryGroupsListResponse>(
    `${businessPath()}?page=${page}&pageSize=${pageSize}`,
    { auth: true, signal },
  )
}

export async function createWebsiteCategoryGroup(payload: CreateWebsiteCategoryGroupPayload) {
  return apiRequest<{ message: string; group: WebsiteCategoryGroup }>(businessPath(), {
    method: 'POST',
    auth: true,
    body: payload,
  })
}

export async function updateWebsiteCategoryGroup(
  groupId: string,
  payload: UpdateWebsiteCategoryGroupPayload,
) {
  return apiRequest<{ message: string; group: WebsiteCategoryGroup }>(
    businessPath(`/${groupId}`),
    {
      method: 'PATCH',
      auth: true,
      body: payload,
    },
  )
}

export async function deleteWebsiteCategoryGroup(groupId: string) {
  return apiRequest<{ message: string }>(businessPath(`/${groupId}`), {
    method: 'DELETE',
    auth: true,
  })
}
