import { createFileRoute } from "@tanstack/react-router";
import { SpotifyWebApiClient } from "@/lib/spotify/client";
import type { SpotifyPlaybackSnapshot } from "@/lib/spotify/types";

export const Route = createFileRoute("/api/spotify/capture")({
  server: {
    handlers: {
      POST: async ({ request }: { request: Request }) => {
        try {
          const cookies = request.headers.get("Cookie") || "";
          const accessTokenMatch = cookies.match(
            /spotify_access_token=([^;]+)/
          );

          if (!accessTokenMatch) {
            return new Response(
              JSON.stringify({ error: "No access token found" }),
              {
                status: 401,
                headers: { "Content-Type": "application/json" },
              }
            );
          }

          const accessToken = decodeURIComponent(accessTokenMatch[1]);
          const spotifyClient = new SpotifyWebApiClient(accessToken);

          const snapshot = await spotifyClient.createPlaybackSnapshot();

          if (!snapshot) {
            return new Response(
              JSON.stringify({ error: "No active playback to capture" }),
              {
                status: 400,
                headers: { "Content-Type": "application/json" },
              }
            );
          }

          return new Response(JSON.stringify({ snapshot }), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (error) {
          console.error("Spotify capture error:", error);

          const errorMessage =
            error instanceof Error
              ? error.message
              : "Failed to capture playback state";

          return new Response(JSON.stringify({ error: errorMessage }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
  },
});
