import { apiRequest } from '../lib/api'
import type { DeployDomainResponse, DomainsListResponse, SyncSslResponse } from '../types/domain'

export interface ListDomainsParams {
  page?: number
  pageSize?: number
  name?: string
}

export interface UpdateDomainPayload {
  host?: string
  expiresAt?: string
}

export async function listDomains(params: ListDomainsParams, signal?: AbortSignal) {
  const q = new URLSearchParams()
  if (params.page !== undefined) q.set('page', String(params.page))
  if (params.pageSize !== undefined) q.set('pageSize', String(params.pageSize))
  if (params.name) q.set('name', params.name)

  const query = q.toString()
  const path = `/domains${query ? `?${query}` : ''}`
  return apiRequest<DomainsListResponse>(path, { auth: true, signal })
}

export async function updateDomain(domainId: number | string, payload: UpdateDomainPayload) {
  return apiRequest(`/domains/${domainId}`, {
    method: 'PATCH',
    auth: true,
    body: payload,
  })
}

export async function setDomainActive(domainId: number | string, isActive: boolean) {
  return apiRequest(`/domains/${domainId}/disable`, {
    method: 'PATCH',
    auth: true,
    body: { isActive },
  })
}

export async function setDomainSsl(domainId: number | string, sslEnabled: boolean) {
  return apiRequest(`/domains/${domainId}/ssl`, {
    method: 'PATCH',
    auth: true,
    body: { sslEnabled },
  })
}

export async function removeDomain(domainId: number | string) {
  return apiRequest(`/domains/${domainId}`, {
    method: 'DELETE',
    auth: true,
  })
}

export async function deployDomain(domainId: number | string) {
  return apiRequest<DeployDomainResponse>(`/domains/${domainId}/deploy`, {
    method: 'POST',
    auth: true,
  })
}

export async function syncSsl() {
  return apiRequest<SyncSslResponse>('/domains/ssl-sync', {
    method: 'POST',
    auth: true,
  })
}
