import { createFileRoute } from "@tanstack/react-router";
import { msg } from "@lingui/core/macro";
import { SpotifyWebApiClient } from "@/lib/spotify/client";
import type { SpotifyPlaybackSnapshot } from "@/lib/spotify/types";
import { localizedFor } from "@/lib/i18n/server-messages";

export const Route = createFileRoute("/api/spotify/resume")({
  server: {
    handlers: {
      POST: async ({ request }: { request: Request }) => {
        // No session middleware on this route; localize with DEFAULT_LOCALE.
        const i18n = localizedFor(null);
        try {
          const cookies = request.headers.get("Cookie") || "";
          const accessTokenMatch = cookies.match(
            /spotify_access_token=([^;]+)/
          );

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

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

          const body = await request.json();
          const { snapshot } = body as { snapshot: SpotifyPlaybackSnapshot };

          if (!snapshot) {
            return new Response(
              JSON.stringify({ error: i18n._(msg`No snapshot provided`) }),
              {
                status: 400,
                headers: { "Content-Type": "application/json" },
              }
            );
          }

          await spotifyClient.restorePlaybackSnapshot(snapshot);

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

          let errorMessage = i18n._(msg`Failed to resume playback state`);

          if (error instanceof Error) {
            if (
              error.message.includes("Premium") ||
              error.message.includes("403")
            ) {
              errorMessage = i18n._(msg`Spotify premium required`);
            } else {
              errorMessage = error.message;
            }
          }

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