import type { Customer } from '../billing/middleware.js';
import type { OAuthCredentials } from '../multitenancy/credential-store.js';

const SNAPCHAT_API_BASE = 'https://api.snapchat.com/v1';

function getEnvToken(account: string): string {
  const envKey = `SNAPCHAT_${account.toUpperCase()}_ACCESS_TOKEN`;
  return process.env[envKey] ?? '';
}

async function resolveToken(args: { account?: string }, customer?: Customer): Promise<string> {
  if (customer) {
    const creds = await customer.getCredential<OAuthCredentials>('snapchat');
    if (!creds) throw new Error('Snapchat not connected for this account');
    return creds.accessToken;
  }
  const token = getEnvToken(args.account ?? 'default');
  if (!token) throw new Error('Missing Snapchat credentials. Set SNAPCHAT_{ACCOUNT}_ACCESS_TOKEN');
  return token;
}

async function snapchatRequest(endpoint: string, accessToken: string) {
  const res = await fetch(`${SNAPCHAT_API_BASE}${endpoint}`, {
    headers: { 'Authorization': `Bearer ${accessToken}` },
    signal: AbortSignal.timeout(15000),
  });

  if (!res.ok) {
    const error = await res.text();
    throw new Error(`Snapchat API error (${res.status}): ${error}`);
  }

  return res.json();
}

export async function getMe(
  args: { account?: string },
  customer?: Customer
): Promise<{
  id: string;
  display_name: string;
  bitmoji_avatar_url?: string;
}> {
  const accessToken = await resolveToken(args, customer);
  const data = await snapchatRequest('/me', accessToken);
  const me = data.data?.me ?? data;

  return {
    id: me.externalId ?? me.id ?? '',
    display_name: me.displayName ?? me.display_name ?? '',
    bitmoji_avatar_url: me.bitmoji?.avatarUrl ?? me.bitmoji_avatar_url,
  };
}

// Snapchat Creative Kit is a mobile-only SDK — there is no server-side
// endpoint for publishing Snaps or Stories. This stub documents that
// constraint rather than silently doing nothing.
export async function createSnap(
  _args: { image_url?: string; video_url?: string; caption?: string; account?: string },
  _customer?: Customer
): Promise<never> {
  throw new Error(
    'Snapchat Creative Kit is a mobile-only SDK — it cannot post Snaps from a server. ' +
    'To share content to Snapchat, integrate the Creative Kit iOS/Android SDK in a mobile app. ' +
    'See https://kit.snapchat.com/creative-kit for docs.'
  );
}

export async function getAdAccounts(
  args: { account?: string },
  customer?: Customer
): Promise<Array<{ id: string; name: string; status: string; currency: string }>> {
  // Snapchat Marketing API — available for ad account management
  const accessToken = await resolveToken(args, customer);
  const data = await snapchatRequest('/me/adaccounts', accessToken);

  return (data.adaccounts ?? []).map((a: Record<string, unknown>) => ({
    id: String((a.adaccount as Record<string, unknown>)?.id ?? a.id ?? ''),
    name: String((a.adaccount as Record<string, unknown>)?.name ?? a.name ?? ''),
    status: String((a.adaccount as Record<string, unknown>)?.status ?? a.status ?? ''),
    currency: String((a.adaccount as Record<string, unknown>)?.currency_code ?? a.currency ?? ''),
  }));
}
