import type { TopicDiscussionConfig } from '@/types/englishSpeaking'

const API_BASE = 'http://localhost:8000/api/speaking/config'

export interface SpeakingConfigRecord {
  id: string
  config: TopicDiscussionConfig
  ownerUid?: string | null
}

async function parse<T>(res: Response): Promise<T> {
  if (!res.ok) {
    const detail = await res.text().catch(() => '')
    throw new Error(`[${res.status}] ${detail || res.statusText}`)
  }
  return res.json() as Promise<T>
}

/** 新建话题讨论配置 */
export async function createSpeakingConfig(
  config: TopicDiscussionConfig,
  ownerUid?: string | null,
): Promise<SpeakingConfigRecord> {
  const res = await fetch(API_BASE, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ config, ownerUid: ownerUid ?? null }),
  })
  return parse<SpeakingConfigRecord>(res)
}

/** 读取话题讨论配置 */
export async function getSpeakingConfig(id: string): Promise<SpeakingConfigRecord> {
  const res = await fetch(`${API_BASE}/${encodeURIComponent(id)}`)
  return parse<SpeakingConfigRecord>(res)
}

/** 更新话题讨论配置 */
export async function updateSpeakingConfig(
  id: string,
  config: TopicDiscussionConfig,
): Promise<SpeakingConfigRecord> {
  const res = await fetch(`${API_BASE}/${encodeURIComponent(id)}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ config }),
  })
  return parse<SpeakingConfigRecord>(res)
}
