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[]
  items?: T[]
  webhooks?: T[]
  total?: number
  page?: number
  page_size?: number
  limit?: number
  offset?: number
}

function normalizeWebhookList(result: PaginatedResponse<RawWebhook>): { data: Webhook[]; total: number; page: number; page_size: number } {
  const rawItems = Array.isArray(result.data)
    ? result.data
    : Array.isArray(result.items)
      ? result.items
      : Array.isArray(result.webhooks)
        ? result.webhooks
        : []
  const data = rawItems.map(normalizeWebhook)
  const pageSize = result.page_size ?? result.limit ?? data.length
  const offset = result.offset ?? 0
  const page = result.page ?? (pageSize > 0 ? Math.floor(offset / pageSize) + 1 : 1)

  return {
    data,
    total: result.total ?? data.length,
    page,
    page_size: pageSize,
  }
}

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>)
  return normalizeWebhookList(result)
}

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>,
  )
}
