/**
 * SSO 单点登录 API
 */
import { request } from '../utils/request'
import type { SSOConfig, SSOSession, SSOLog, SSOProvider, SyncDirection } from '../types/sso'

// ==================== SSO 配置 ====================

/** 获取 SSO 配置 */
export const getSSOConfig = (enterpriseId: number) => {
  return request<SSOConfig>({
    url: `/enterprise/sso/config/${enterpriseId}`,
    method: 'GET',
  })
}

/** 创建 SSO 配置 */
export const createSSOConfig = (data: Omit<SSOConfig, 'id' | 'createTime' | 'updateTime'>) => {
  return request<SSOConfig>({
    url: '/enterprise/sso/config',
    method: 'POST',
    data,
  })
}

/** 更新 SSO 配置 */
export const updateSSOConfig = (data: Partial<SSOConfig> & { id: number }) => {
  return request<SSOConfig>({
    url: '/enterprise/sso/config',
    method: 'PUT',
    data,
  })
}

/** 删除 SSO 配置 */
export const deleteSSOConfig = (id: number) => {
  return request<void>({
    url: `/enterprise/sso/config/${id}`,
    method: 'DELETE',
  })
}

/** 启用/禁用 SSO */
export const toggleSSO = (id: number, enabled: boolean) => {
  return request<void>({
    url: `/enterprise/sso/config/${id}/toggle`,
    method: 'POST',
    data: { enabled },
  })
}

/** 测试 SSO 连接 */
export const testSSOConnection = (id: number) => {
  return request<{ success: boolean; message: string }>({
    url: `/enterprise/sso/config/${id}/test`,
    method: 'POST',
  })
}

/** 生成 SSO 登录链接 */
export const getSSOLoginUrl = (id: number, redirectUri?: string) => {
  return request<{ url: string }>({
    url: `/enterprise/sso/config/${id}/login-url`,
    method: 'GET',
    params: { redirectUri },
  })
}

// ==================== SSO 会话 ====================

/** 获取 SSO 会话列表 */
export const pageSSOSessions = (params: { enterpriseId: number; page?: number; limit?: number }) => {
  return request<{ list: SSOSession[]; total: number }>({
    url: '/enterprise/sso/sessions',
    method: 'GET',
    params,
  })
}

/** 强制下线 SSO 会话 */
export const logoutSSOSession = (id: number) => {
  return request<void>({
    url: `/enterprise/sso/sessions/${id}/logout`,
    method: 'POST',
  })
}

/** 强制下线所有 SSO 会话 */
export const logoutAllSSOSessions = (enterpriseId: number) => {
  return request<void>({
    url: `/enterprise/sso/sessions/logout-all`,
    method: 'POST',
    data: { enterpriseId },
  })
}

// ==================== SSO 日志 ====================

/** 获取 SSO 日志列表 */
export const pageSSOLogs = (params: {
  enterpriseId: number
  page?: number
  limit?: number
  type?: string
  status?: string
  timeStart?: string
  timeEnd?: string
}) => {
  return request<{ list: SSOLog[]; total: number }>({
    url: '/enterprise/sso/logs',
    method: 'GET',
    params,
  })
}
