import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'
import type {
  CreateWebsiteBrandGroupPayload,
  UpdateWebsiteBrandGroupPayload,
  WebsiteBrandGroup,
  WebsiteBrandGroupsListResponse,
} from '../types/websiteBrandGroup'

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

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

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

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

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