import { createFileRoute } from "@tanstack/react-router";

async function getClientCredentialsToken(): Promise<string> {
  const clientId = process.env.VITE_SPOTIFY_CLIENT_ID;
  const clientSecret = process.env.SPOTIFY_CLIENT_SECRET;

  if (!clientId || !clientSecret) {
    throw new Error("Missing Spotify client credentials");
  }

  const response = await fetch("https://accounts.spotify.com/api/token", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`,
    },
    body: "grant_type=client_credentials",
  });

  if (!response.ok) {
    throw new Error("Failed to get Spotify access token");
  }

  const data = await response.json();
  return data.access_token;
}

export const Route = createFileRoute("/api/spotify/search")({
  server: {
    handlers: {
      GET: async ({ request }: { request: Request }) => {
        try {
          const url = new URL(request.url);
          const query = url.searchParams.get("q");

          if (!query) {
            return new Response(
              JSON.stringify({ error: "Query parameter q is required" }),
              {
                status: 400,
                headers: { "Content-Type": "application/json" },
              }
            );
          }

          // Get client credentials access token
          const accessToken = await getClientCredentialsToken();

          // Search using Spotify API directly
          const searchUrl = `https://api.spotify.com/v1/search?q=${encodeURIComponent(query)}&type=track&limit=20`;

          const searchResponse = await fetch(searchUrl, {
            headers: {
              Authorization: `Bearer ${accessToken}`,
            },
          });

          if (!searchResponse.ok) {
            throw new Error("Spotify search request failed");
          }

          const searchResult = await searchResponse.json();

          return new Response(
            JSON.stringify({ tracks: searchResult.tracks.items }),
            {
              status: 200,
              headers: { "Content-Type": "application/json" },
            }
          );
        } catch (error) {
          console.error("Search error:", error);
          return new Response(
            JSON.stringify({
              error: "Search failed",
              details: error instanceof Error ? error.message : "Unknown error",
            }),
            {
              status: 500,
              headers: { "Content-Type": "application/json" },
            }
          );
        }
      },
    },
  },
});
