import { api } from '@/core/services/api'
import type {
  ExternalSystem,
  ExternalSystemListResponse,
  ExternalSystemResponse,
  ExternalSystemSsoLaunchResponse,
} from '../types/external-system.types'

export async function listExternalSystems(): Promise<ExternalSystem[]> {
  const { data } = await api.get<ExternalSystemListResponse>('/v1/external-systems')

  if (!data.success) {
    throw new Error(data.message ?? 'Gagal memuatkan senarai sistem luaran.')
  }

  return data.data
}

export async function getExternalSystem(id: string): Promise<ExternalSystem> {
  const { data } = await api.get<ExternalSystemResponse>(`/v1/external-systems/${id}`)

  if (!data.success) {
    throw new Error(data.message ?? 'Sistem luaran tidak dijumpai.')
  }

  return data.data
}

export async function launchExternalSystemSso(
  systemCode: string,
): Promise<ExternalSystemSsoLaunchResponse> {
  const { data } = await api.post<ExternalSystemSsoLaunchResponse>(
    `/v1/external-systems/${systemCode}/sso/launch`,
  )

  if (!data.success) {
    throw new Error(data.message ?? 'Gagal membuka sistem.')
  }

  return data
}
