import { NextRequest, NextResponse } from "next/server";
import { hasProFeatures } from "@/lib/edition";
import { getSessionUser } from "@/lib/session";
import { parseCreatePlaylistInput } from "@/lib/jobs/resolve-playlist";
import { createYouTubePlaylist, listYouTubePlaylists } from "@/lib/youtube/upload";

async function requirePremiumYouTubeUser() {
  const user = await getSessionUser();
  if (!user) {
    return { error: NextResponse.json({ error: "Unauthorized" }, { status: 401 }), user: null };
  }
  if (!hasProFeatures(user.plan)) {
    return {
      error: NextResponse.json(
        { error: "Playlist features are available on the Pro plan only" },
        { status: 403 },
      ),
      user: null,
    };
  }
  if (!user.youtubeConnection) {
    return {
      error: NextResponse.json({ error: "YouTube account not connected" }, { status: 403 }),
      user: null,
    };
  }
  return { error: null, user };
}

export async function GET() {
  const { error, user } = await requirePremiumYouTubeUser();
  if (error || !user) return error!;

  try {
    const playlists = await listYouTubePlaylists(user.id);
    return NextResponse.json({ playlists });
  } catch (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 requirePremiumYouTubeUser();
  if (error || !user) return error!;

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

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