import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'
import type {
  BrandApi,
  BrandFormData,
  BrandsListResponse,
  CreateBrandPayload,
  UpdateBrandPayload,
} from '../types/brand'
import type { FlatCategory } from '../types/category'

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

export async function listBrands(
  page = 1,
  pageSize = 100,
  signal?: AbortSignal,
  filters?: { name?: string },
) {
  const params = new URLSearchParams({
    page: String(page),
    pageSize: String(pageSize),
  })
  if (filters?.name?.trim()) {
    params.set('name', filters.name.trim())
  }

  return apiRequest<BrandsListResponse>(`${businessPath()}?${params.toString()}`, {
    auth: true,
    signal,
  })
}

export async function listAllBrands(signal?: AbortSignal) {
  const pageSize = 100
  let page = 1
  let items: BrandApi[] = []
  let total = Infinity

  while (items.length < total) {
    const data = await listBrands(page, pageSize, signal)
    items = items.concat(data.items)
    total = data.total
    page += 1
  }

  return items
}

export async function createBrand(payload: CreateBrandPayload) {
  return apiRequest<{ message: string; brand: BrandApi }>(businessPath(), {
    method: 'POST',
    auth: true,
    body: payload,
  })
}

export async function updateBrand(brandId: string, payload: UpdateBrandPayload) {
  return apiRequest<{ message: string; brand: BrandApi }>(businessPath(`/${brandId}`), {
    method: 'PATCH',
    auth: true,
    body: payload,
  })
}

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

export function toBrandFormPayload(
  data: BrandFormData,
  imageMediaId?: string | null,
): CreateBrandPayload {
  return {
    nameEn: data.nameEn,
    nameFa: data.nameFa || undefined,
    about: data.about || undefined,
    ...(imageMediaId ? { imageMediaId } : {}),
  }
}

export function mapBrandApiToUi(brand: BrandApi) {
  return {
    id: brand.id,
    nameEn: brand.nameEn,
    nameFa: brand.nameFa ?? '',
    about: brand.about ?? '',
    slug: brand.slug,
    imageUrl: brand.imageUrl,
    imageMediaId: brand.imageMediaId,
  }
}

export function mapBrandToSelectOption(brand: BrandApi): FlatCategory {
  return {
    id: brand.id,
    nameEn: brand.nameEn,
    nameFa: brand.nameFa ?? '',
    description: brand.about ?? '',
    parentId: null,
    variationCount: 0,
    depth: 0,
  }
}
