import { getYouTubeConfig } from "@/lib/env";

const AUTH = "https://accounts.google.com/o/oauth2/v2/auth";
const TOKEN = "https://oauth2.googleapis.com/token";
const YT = "https://www.googleapis.com/youtube/v3";

export function buildYouTubeAuthUrl(state: string): string {
  const { clientId, redirectUri, scopes } = getYouTubeConfig();
  if (!clientId || !redirectUri) throw new Error("YouTube (Google) OAuth is not configured");

  const params = new URLSearchParams({
    client_id: clientId,
    redirect_uri: redirectUri,
    response_type: "code",
    scope: scopes,
    state,
    access_type: "offline",
    prompt: "consent",
  });

  return `${AUTH}?${params.toString()}`;
}

export async function exchangeYouTubeCode(code: string): Promise<{
  accessToken: string;
  refreshToken?: string;
  expiresIn?: number;
}> {
  const { clientId, clientSecret, redirectUri } = getYouTubeConfig();
  const body = new URLSearchParams({
    code,
    client_id: clientId,
    client_secret: clientSecret,
    redirect_uri: redirectUri,
    grant_type: "authorization_code",
  });

  const res = await fetch(TOKEN, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body });
  const data = (await res.json()) as {
    access_token?: string;
    refresh_token?: string;
    expires_in?: number;
    error_description?: string;
  };

  if (!res.ok || !data.access_token) {
    throw new Error(data.error_description ?? "YouTube token exchange failed");
  }

  return {
    accessToken: data.access_token,
    refreshToken: data.refresh_token,
    expiresIn: data.expires_in,
  };
}

export async function refreshYouTubeToken(refreshToken: string): Promise<{
  accessToken: string;
  expiresIn?: number;
}> {
  const { clientId, clientSecret } = getYouTubeConfig();
  const body = new URLSearchParams({
    client_id: clientId,
    client_secret: clientSecret,
    refresh_token: refreshToken,
    grant_type: "refresh_token",
  });

  const res = await fetch(TOKEN, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body });
  const data = (await res.json()) as { access_token?: string; expires_in?: number; error_description?: string };
  if (!res.ok || !data.access_token) {
    throw new Error(data.error_description ?? "YouTube token refresh failed");
  }
  return { accessToken: data.access_token, expiresIn: data.expires_in };
}

export async function fetchYouTubeChannel(accessToken: string): Promise<{
  channelId: string;
  title: string;
}> {
  const res = await fetch(`${YT}/channels?part=snippet&mine=true`, {
    headers: { Authorization: `Bearer ${accessToken}` },
  });
  const data = (await res.json()) as {
    items?: Array<{ id: string; snippet?: { title?: string } }>;
    error?: { message?: string };
  };

  if (!res.ok || !data.items?.[0]?.id) {
    throw new Error(data.error?.message ?? "No YouTube channel found for this Google account");
  }

  return {
    channelId: data.items[0].id,
    title: data.items[0].snippet?.title ?? "YouTube Channel",
  };
}
