import { get, post, put, del } from '@/lib/http/client'
import type { Webhook } from '@/types/webhook'
import type {
  CreateWebhookRequest,
  UpdateWebhookRequest,
  WebhookListParams,
  WebhookDelivery,
  WebhookDeliveryListParams,
} from '@/types/webhook'

interface RawWebhook extends Omit<Webhook, 'events'> {
  events: string | string[]
}

function parseEvents(value: string | string[]): Webhook['events'] {
  if (Array.isArray(value)) {
    return value as Webhook['events']
  }

  try {
    const parsed = JSON.parse(value)
    return Array.isArray(parsed) ? (parsed as Webhook['events']) : []
  } catch {
    return []
  }
}

function normalizeWebhook(webhook: RawWebhook): Webhook {
  return {
    ...webhook,
    events: parseEvents(webhook.events),
  }
}

interface PaginatedResponse<T> {
  data: T[]
  total: number
  page: number
  page_size: number
}

export async function listWebhooks(
  params?: WebhookListParams,
): Promise<{ data: Webhook[]; total: number; page: number; page_size: number }> {
  const result = await get<PaginatedResponse<RawWebhook>>('/webhooks', params as Record<string, string | number | boolean | undefined>)
  const webhooks = result.data.map(normalizeWebhook)
  return { data: webhooks, total: result.total, page: result.page, page_size: result.page_size }
}

export function createWebhook(data: CreateWebhookRequest): Promise<Webhook> {
  return post<RawWebhook>('/webhooks', data).then(normalizeWebhook)
}

export function updateWebhook(id: number, data: UpdateWebhookRequest): Promise<void> {
  return put<void>(`/webhooks/${id}`, data)
}

export function deleteWebhook(id: number): Promise<void> {
  return del<void>(`/webhooks/${id}`)
}

export function updateWebhookStatus(id: number, status: 0 | 1): Promise<void> {
  return updateWebhook(id, { status })
}

export function getWebhookDeliveries(
  id: number,
  params?: WebhookDeliveryListParams,
): Promise<WebhookDelivery[]> {
  return get<WebhookDelivery[]>(
    `/webhooks/${id}/deliveries`,
    params as Record<string, string | number | boolean | undefined>,
  )
}
