import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'
import type {
  CategoryFormData,
  CreateCategoryPayload,
  ProductCategoriesResponse,
  ProductCategory,
  UpdateCategoryPayload,
} from '../types/category'

const ENTITY_TYPE = 'blog' as const

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

export async function listBlogCategories(signal?: AbortSignal) {
  const data = await apiRequest<ProductCategoriesResponse>(
    `${businessPath()}?entityType=${ENTITY_TYPE}`,
    { auth: true, signal },
  )
  return data.items
}

export async function createBlogCategory(payload: CreateCategoryPayload) {
  return apiRequest<{ message: string; category: ProductCategory }>(businessPath(), {
    method: 'POST',
    auth: true,
    body: { ...payload, entityType: ENTITY_TYPE },
  })
}

export async function updateBlogCategory(categoryId: string, payload: UpdateCategoryPayload) {
  return apiRequest<{ message: string; category: ProductCategory }>(
    businessPath(`/${categoryId}`),
    {
      method: 'PATCH',
      auth: true,
      body: payload,
    },
  )
}

export async function deleteBlogCategory(categoryId: string) {
  return apiRequest<{ message: string; deletedIds: string[] }>(
    businessPath(`/${categoryId}`),
    {
      method: 'DELETE',
      auth: true,
    },
  )
}

export function toBlogCategoryFormPayload(data: CategoryFormData): CreateCategoryPayload {
  return {
    parentId: data.parentId || undefined,
    name: data.nameEn,
    nameFa: data.nameFa,
    description: data.description || undefined,
  }
}

export function mapBlogCategoryToUi(category: ProductCategory) {
  return {
    id: category.id,
    nameEn: category.name,
    nameFa: category.nameFa ?? '',
    description: category.description ?? '',
    parentId: category.parentId,
    variationCount: category.variationCount ?? 0,
  }
}
