import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'
import type { StoreSpecial } from '../types/storeSpecial'

export interface StoreSpecialsListResponse {
  items: StoreSpecial[]
  total: number
  page: number
  pageSize: number
}

export interface CreateStoreSpecialPayload {
  key: string
  title: string
  storeItemIds?: string[]
  sortOrder?: number
  isActive?: boolean
}

export interface UpdateStoreSpecialPayload {
  key?: string
  title?: string
  storeItemIds?: string[]
  sortOrder?: number
  isActive?: boolean
}

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

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

export async function createStoreSpecial(payload: CreateStoreSpecialPayload) {
  return apiRequest<{ message: string; special: StoreSpecial }>(businessPath(), {
    method: 'POST',
    auth: true,
    body: payload,
  })
}

export async function updateStoreSpecial(specialId: string, payload: UpdateStoreSpecialPayload) {
  return apiRequest<{ message: string; special: StoreSpecial }>(businessPath(`/${specialId}`), {
    method: 'PATCH',
    auth: true,
    body: payload,
  })
}

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