"use server";

import {
  InternetProviderLyricSearchResponse,
  getSearchResults,
} from "@/lib/actions/lyrics";
import { revalidateTag } from "next/cache";
import { LyricSource } from "@/lib/types";
import { cookies } from "next/headers";

export async function searchSongs(
  _currentState: InternetProviderLyricSearchResponse[],
  formData: FormData
): Promise<InternetProviderLyricSearchResponse[]> {
  const list = await getSearchResults({
    name: formData.get("name") as string,
  });
  if (list) {
    return list;
  }
  return [];
}

export async function addSong(
  _: unknown,
  item: InternetProviderLyricSearchResponse
) {
  const token = cookies().get("token");
  await fetch("https://tachy.daoyoucloud.com/api/songs:create", {
    method: "POST",
    headers: {
      "X-App": "danmu-sim",
      "X-Authenticator": "basic",
      authorization: "Bearer " + token?.value,
      "content-type": "application/json",
    },
    body: JSON.stringify({
      artist: item.artist,
      name: item.name,
      source: LyricSource.NETEASE,
      source_id: item.id,
    }),
  });
  revalidateTag("songs");
}

export async function listSongs(): Promise<any[]> {
  const token = cookies().get("token");
  const params = new URLSearchParams();
  params.append("pageSize", "99999");
  params.append(
    "filter",
    JSON.stringify({ $and: [{ createdBy: { id: { $eq: "{{$user.id}}" } } }] })
  );
  const songs = await fetch(
    "https://tachy.daoyoucloud.com/api/songs:list?" + params.toString(),
    {
      method: "GET",
      headers: {
        "X-App": "danmu-sim",
        "X-Authenticator": "basic",
        authorization: "Bearer " + token?.value,
        "content-type": "application/json",
      },
      next: {
        tags: ["songs"],
      },
    }
  );
  const result = await songs.json();
  return result?.data ?? [];
}

export async function deleteSong(id: number): Promise<void> {
  const token = cookies().get("token");
  const params = new URLSearchParams();
  params.append('filterByTk', id.toString());
  await fetch(
    "https://tachy.daoyoucloud.com/api/songs:destroy?" + params.toString(),
    {
      method: "GET",
      headers: {
        "X-App": "danmu-sim",
        "X-Authenticator": "basic",
        authorization: "Bearer " + token?.value,
        "content-type": "application/json",
      },
    }
  );
  revalidateTag("songs");
}
