import { getAppUrl } from "@/lib/env";

export function getPinterestRedirectUri() {
  return (
    process.env.PINTEREST_REDIRECT_URI ??
    process.env.PINTEREST_SOCIAL_REDIRECT_URI ??
    `${getAppUrl()}/connected-accounts/oauth/pinterest/callback`
  );
}

export function getPinterestConfig() {
  return {
    appId:
      process.env.PINTEREST_APP_ID?.trim() ||
      process.env.PINTEREST_CLIENT_ID?.trim() ||
      "",
    appSecret:
      process.env.PINTEREST_APP_SECRET?.trim() ||
      process.env.PINTEREST_CLIENT_SECRET?.trim() ||
      "",
    redirectUri: getPinterestRedirectUri(),
    scopes: (
      process.env.PINTEREST_SCOPES?.trim() ||
      "boards:read,boards:write,pins:read,pins:write,user_accounts:read"
    )
      .split(/[,\s]+/)
      .filter(Boolean),
    apiBase: "https://api.pinterest.com/v5",
  };
}

export function buildPinterestAuthUrl(state: string): string {
  const { appId, redirectUri, scopes } = getPinterestConfig();
  if (!appId) throw new Error("Pinterest OAuth is not configured");
  const params = new URLSearchParams({
    client_id: appId,
    redirect_uri: redirectUri,
    response_type: "code",
    scope: scopes.join(","),
    state,
  });
  return `https://www.pinterest.com/oauth/?${params.toString()}`;
}

export async function exchangePinterestCode(code: string): Promise<{
  accessToken: string;
  refreshToken?: string;
  expiresIn?: number;
}> {
  const { appId, appSecret, redirectUri } = getPinterestConfig();
  const basic = Buffer.from(`${appId}:${appSecret}`).toString("base64");
  const body = new URLSearchParams({
    grant_type: "authorization_code",
    code,
    redirect_uri: redirectUri,
  });
  const res = await fetch("https://api.pinterest.com/v5/oauth/token", {
    method: "POST",
    headers: {
      Authorization: `Basic ${basic}`,
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: body.toString(),
  });
  const data = (await res.json()) as {
    access_token?: string;
    refresh_token?: string;
    expires_in?: number;
    message?: string;
    code?: number;
  };
  if (!res.ok || !data.access_token) {
    throw new Error(data.message || "Pinterest token exchange failed");
  }
  return {
    accessToken: data.access_token,
    refreshToken: data.refresh_token,
    expiresIn: data.expires_in,
  };
}

export async function fetchPinterestUser(accessToken: string): Promise<{
  username: string;
  id: string;
}> {
  const { apiBase } = getPinterestConfig();
  const res = await fetch(`${apiBase}/user_account`, {
    headers: { Authorization: `Bearer ${accessToken}` },
  });
  const data = (await res.json()) as {
    username?: string;
    id?: string;
    message?: string;
  };
  if (!res.ok) {
    throw new Error(data.message || "Failed to load Pinterest user");
  }
  return {
    username: data.username || "Pinterest user",
    id: data.id || data.username || "pinterest",
  };
}

export async function getOrCreateDefaultBoard(
  accessToken: string,
): Promise<string> {
  const { apiBase } = getPinterestConfig();
  const listRes = await fetch(`${apiBase}/boards?page_size=25`, {
    headers: { Authorization: `Bearer ${accessToken}` },
  });
  const listData = (await listRes.json()) as {
    items?: Array<{ id: string; name?: string }>;
    message?: string;
  };
  if (listRes.ok && listData.items?.length) {
    const preferred =
      listData.items.find((b) => /postsync|social|pins/i.test(b.name || "")) ||
      listData.items[0];
    if (preferred?.id) return preferred.id;
  }

  const createRes = await fetch(`${apiBase}/boards`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${accessToken}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      name: "PostSync Pro",
      description: "Pins published from PostSync Pro",
      privacy: "PUBLIC",
    }),
  });
  const created = (await createRes.json()) as { id?: string; message?: string };
  if (!createRes.ok || !created.id) {
    throw new Error(created.message || "Could not create a Pinterest board");
  }
  return created.id;
}
