import type { CourseList, CourseListParams, CourseRow, FitnessGroup, YesNo } from './types'
import { api } from './client'

/**
 * 課程建議的 5 支 API。
 * 端點路徑集中在此檔，後端定案後只需改這裡。
 */

/**
 * course/list 實際回傳格式：weekdayCode（"0"=週日…"6"=週六）與 weekdayText，
 * 與 doc/課程建議API規格.md 記載的 `{ day, morning, noon, night }` 不同，故在此轉換。
 */
interface CourseListApiRow {
  weekdayCode: string
  weekdayText: string
  morning: string
  noon: string
  night: string
}

/** weekdayCode 轉換為前端沿用的 1（週一）…7（週日）編號 */
function toDay (weekdayCode: string): number {
  const code = Number(weekdayCode)
  return code === 0 ? 7 : code
}

/** 未勾選的時段後端回傳空字串，轉為 undefined 以符合 CourseRow 的選填語意 */
function toCourseRow (raw: CourseListApiRow): CourseRow {
  return {
    day: toDay(raw.weekdayCode),
    morning: raw.morning || undefined,
    noon: raw.noon || undefined,
    night: raw.night || undefined,
  }
}

/** 依登入取得的 userID 查詢體適能組別 */
export function fetchGroup (userID: string): Promise<FitnessGroup> {
  return api.get('course/group', { searchParams: { userID } }).json<FitnessGroup>()
}

/** 取得是否納入早上時段 */
export function fetchMorning (group: FitnessGroup): Promise<YesNo> {
  return api.get('course/morning', { searchParams: { group } }).json<YesNo>()
}

/** 取得是否納入中午時段 */
export function fetchNoon (group: FitnessGroup): Promise<YesNo> {
  return api.get('course/noon', { searchParams: { group } }).json<YesNo>()
}

/** 取得是否納入晚上時段 */
export function fetchNight (group: FitnessGroup): Promise<YesNo> {
  return api.get('course/night', { searchParams: { group } }).json<YesNo>()
}

/** 以組別與時段條件取得一週課表 */
export async function fetchCourseList (params: CourseListParams): Promise<CourseList> {
  const rows = await api
    .get('course/list', { searchParams: { ...params } })
    .json<CourseListApiRow[]>()

  return rows.map(row => toCourseRow(row))
}
