import { NextRequest, NextResponse } from "next/server";
import { requireApiUser } from "@/lib/api-auth";
import { parseCreatePlaylistInput } from "@/lib/jobs/resolve-playlist";
import { createYouTubePlaylist, listYouTubePlaylists } from "@/lib/youtube/upload";

export async function GET(req: NextRequest) {
  const { error, user } = await requireApiUser(req);
  if (error || !user) return error!;

  try {
    const playlists = await listYouTubePlaylists(user.id);
    return NextResponse.json({ playlists });
  } catch (err) {
    console.error("List playlists failed:", err);
    const message = err instanceof Error ? err.message : "Failed to list playlists";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}

export async function POST(req: NextRequest) {
  const { error, user } = await requireApiUser(req);
  if (error || !user) return error!;

  try {
    const body = await req.json();
    const input = parseCreatePlaylistInput(body);
    if (!input) {
      return NextResponse.json(
        {
          error:
            "Provide JSON body: { title, description?, privacy? } where privacy is public|unlisted|private",
        },
        { status: 400 },
      );
    }

    const playlist = await createYouTubePlaylist(user.id, input);
    return NextResponse.json({ playlist });
  } catch (err) {
    console.error("Create playlist failed:", err);
    const message = err instanceof Error ? err.message : "Failed to create playlist";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
