import { generateSecureToken } from '@/lib/crypto/encryption';
import { env } from '@/lib/config/env';

const META_OAUTH_SCOPES = [
  'public_profile',
  'email',
  'catalog_management',
  'ads_management',
  'business_management'
];

/**
 * Builds the Meta Business OAuth dialog URL.
 */
export function buildMetaAuthUrl(shopId: string, redirectUri: string): { url: string; state: string } {
  const appId = env.meta.appId;
  const state = `${shopId}:${generateSecureToken(16)}`;
  const scopeStr = META_OAUTH_SCOPES.join(',');

  const url = `https://www.facebook.com/${env.meta.graphVersion}/dialog/oauth?client_id=${encodeURIComponent(appId)}&redirect_uri=${encodeURIComponent(redirectUri)}&state=${encodeURIComponent(state)}&scope=${encodeURIComponent(scopeStr)}&response_type=code`;

  return { url, state };
}

/**
 * Exchanges authorization code for a long-lived Meta Business Access Token.
 */
export async function exchangeMetaAuthCode(code: string, redirectUri: string): Promise<{
  access_token: string;
  expires_in?: number;
}> {
  const appId = env.meta.appId;
  const appSecret = env.meta.appSecret;

  if (!appId || !appSecret) {
    throw new Error('Meta App ID or App Secret not configured in environment');
  }

  const url = `https://graph.facebook.com/${env.meta.graphVersion}/oauth/access_token?client_id=${encodeURIComponent(appId)}&redirect_uri=${encodeURIComponent(redirectUri)}&client_secret=${encodeURIComponent(appSecret)}&code=${encodeURIComponent(code)}`;

  const res = await fetch(url);
  const data = await res.json();
  if (!res.ok || data.error) {
    throw new Error(data.error?.message || 'Failed to exchange Meta OAuth code');
  }

  return {
    access_token: data.access_token,
    expires_in: data.expires_in,
  };
}
