import api from './client'

export interface Tenant {
  id: string
  name: string
  slug: string
  is_active: boolean
  user_count?: number
  created_at: string
}

export interface TenantCreate {
  name: string
  slug: string
  is_active?: boolean
}

export interface TenantUpdate {
  name?: string
  slug?: string
  is_active?: boolean
}

export interface TenantAIConfig {
  ai_enabled: boolean
  ai_endpoint: string | null
  ai_deployment: string
  ai_api_version: string
  has_api_key: boolean
  ai_max_tokens: number
  ai_temperature: number
  ai_validation_prompt: string | null
}

export interface TenantAIConfigUpdate {
  ai_enabled: boolean
  ai_endpoint?: string | null
  ai_deployment?: string
  ai_api_version?: string
  ai_api_key?: string | null
  ai_max_tokens?: number
  ai_temperature?: number
  ai_validation_prompt?: string | null
}

export async function getTenants(): Promise<Tenant[]> {
  const res = await api.get<Tenant[]>('/tenants/')
  return res.data
}

export async function getTenant(id: string): Promise<Tenant> {
  const res = await api.get<Tenant>(`/tenants/${id}`)
  return res.data
}

export async function createTenant(data: TenantCreate): Promise<Tenant> {
  const res = await api.post<Tenant>('/tenants', data)
  return res.data
}

export async function updateTenant(id: string, data: TenantUpdate): Promise<Tenant> {
  const res = await api.patch<Tenant>(`/tenants/${id}`, data)
  return res.data
}

export async function deleteTenant(id: string): Promise<void> {
  await api.delete(`/tenants/${id}`)
}

export async function getTenantAIConfig(tenantId: string): Promise<TenantAIConfig> {
  const res = await api.get<TenantAIConfig>(`/tenants/${tenantId}/ai-config`)
  return res.data
}

export async function updateTenantAIConfig(
  tenantId: string,
  config: TenantAIConfigUpdate,
): Promise<TenantAIConfig> {
  const res = await api.put<TenantAIConfig>(`/tenants/${tenantId}/ai-config`, config)
  return res.data
}

export async function testTenantAIConfig(
  tenantId: string,
): Promise<{ ok: boolean; error?: string }> {
  const res = await api.post<{ ok: boolean; error?: string }>(
    `/tenants/${tenantId}/ai-config/test`,
  )
  return res.data
}
