import crypto from 'crypto';

const SECRET = process.env.NEXT_PUBLIC_INVITE_SECRET!;

const toBase64Url = (str: string) =>
  Buffer.from(str).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');

const fromBase64Url = (str: string) =>
  Buffer.from(str.replace(/-/g, '+').replace(/_/g, '/').padEnd(str.length + (4 - str.length % 4) % 4, '='), 'base64').toString('utf8');

export function generateInviteLink(portfolioId: string): string {
  const payload = toBase64Url(JSON.stringify({ p: portfolioId }));
  const signature = toBase64Url(
    crypto.createHmac('sha256', SECRET).update(payload).digest('base64')
  );
  return `${process.env.NEXT_PUBLIC_FRONTEND_URL}/register?invite=${payload}.${signature}`;
}

export function validateInviteToken(token: string): string | null {
  const [payload, signature] = token.split('.');
  if (!payload || !signature) return null;

  const expected = toBase64Url(
    crypto.createHmac('sha256', SECRET).update(payload).digest('base64')
  );
  if (signature !== expected) return null;

  try {
    const { p } = JSON.parse(fromBase64Url(payload));
    return p;
  } catch {
    return null;
  }
}