import type { Song as ApiSong } from "./types"
import type { Song as ComponentSong } from "@/components/songs/song-detail-dialog"

/**
 * 将API歌曲类型转换为组件歌曲类型
 */
export function apiSongToComponentSong(apiSong: ApiSong): ComponentSong {
  // 优先使用rawData中的数据，这样可以确保编辑时加载所有原始数据
  const rawData = apiSong.rawData;
  const attributes = rawData?.attributes || {};
  
  return {
    id: apiSong.id,
    name: apiSong.name,
    composer: apiSong.composer || attributes.composer || "",
    lyricist: apiSong.lyricist || attributes.lyricist || "",
    duration: apiSong.duration || attributes.duration || "",
    releaseDate: apiSong.releaseDate,
    status: apiSong.status || rawData?.status_display || "",
    image: apiSong.image || rawData?.image_url || undefined,
    audioUrl: apiSong.audioUrl || attributes.audio_file || "",
    description: apiSong.description || rawData?.description || "",
    rarity: apiSong.rarity || rawData?.rarity_display || "",
    cardType: apiSong.cardType || rawData?.card_type_display || "",
    genre: apiSong.genre || attributes.genre || "",
    lyrics: apiSong.lyrics || attributes.lyrics || "",
    bpm: apiSong.bpm || attributes.bpm || 0
  }
}

/**
 * 将组件歌曲类型转换为API歌曲类型，保留原始数据
 */
export function componentSongToApiSong(componentSong: ComponentSong, originalApiSong?: ApiSong): ApiSong {
  // 获取原始数据
  const rawData = originalApiSong?.rawData;
  
  return {
    id: componentSong.id,
    name: componentSong.name,
    composer: componentSong.composer,
    lyricist: componentSong.lyricist,
    duration: componentSong.duration,
    releaseDate: componentSong.releaseDate,
    status: componentSong.status,
    image: componentSong.image,
    audioUrl: componentSong.audioUrl,
    description: componentSong.description,
    rarity: componentSong.rarity,
    cardType: componentSong.cardType,
    genre: componentSong.genre,
    lyrics: componentSong.lyrics,
    bpm: typeof componentSong.bpm === 'string' ? parseInt(componentSong.bpm, 10) : componentSong.bpm,
    // 保留原始数据
    rawData: rawData ? {
      ...rawData,
      // 更新原始数据中的相关字段
      name: componentSong.name,
      description: componentSong.description || rawData.description,
      attributes: {
        ...rawData.attributes,
        composer: componentSong.composer,
        lyricist: componentSong.lyricist,
        duration: componentSong.duration,
        genre: componentSong.genre,
        lyrics: componentSong.lyrics,
        bpm: typeof componentSong.bpm === 'string' ? parseInt(componentSong.bpm, 10) : componentSong.bpm,
        audio_file: componentSong.audioUrl
      }
    } : undefined
  }
} 