import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'
import type {
  CreateWebsiteSliderPayload,
  UpdateWebsiteSliderPayload,
  WebsiteSlider,
  WebsiteSlidersListResponse,
} from '../types/websiteSlider'

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

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

export async function createWebsiteSlider(payload: CreateWebsiteSliderPayload) {
  return apiRequest<{ message: string; slider: WebsiteSlider }>(businessPath(), {
    method: 'POST',
    auth: true,
    body: payload,
  })
}

export async function updateWebsiteSlider(sliderId: string, payload: UpdateWebsiteSliderPayload) {
  return apiRequest<{ message: string; slider: WebsiteSlider }>(businessPath(`/${sliderId}`), {
    method: 'PATCH',
    auth: true,
    body: payload,
  })
}

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

export function slidesToPayload(
  slides: Array<{
    imageMediaId: string
    title?: string | null
    linkUrl?: string | null
    isActive?: boolean
  }>,
) {
  return slides.map((slide) => ({
    imageMediaId: slide.imageMediaId,
    ...(slide.title ? { title: slide.title } : {}),
    ...(slide.linkUrl ? { linkUrl: slide.linkUrl } : {}),
    isActive: slide.isActive ?? true,
  }))
}
