import { randomBytes, createHash } from 'crypto';
import { config } from './config.js';

const CSRF_SECRET = config.CSRF_SECRET;

export function generateCsrfToken(sessionId: string): string {
  const timestamp = Date.now().toString();
  const data = `${sessionId}:${timestamp}`;
  const hash = createHash('sha256')
    .update(CSRF_SECRET)
    .update(data)
    .digest('hex');
  return Buffer.from(`${data}:${hash}`).toString('base64');
}

export function validateCsrfToken(token: string, sessionId: string): boolean {
  try {
    const decoded = Buffer.from(token, 'base64').toString('utf-8');
    const [tokenSessionId, timestamp, hash] = decoded.split(':');

    if (tokenSessionId !== sessionId) {
      return false;
    }

    const tokenTime = parseInt(timestamp, 10);
    const now = Date.now();
    const tokenAge = now - tokenTime;

    if (tokenAge > 3600000) {
      return false;
    }

    const expectedHash = createHash('sha256')
      .update(CSRF_SECRET)
      .update(`${tokenSessionId}:${timestamp}`)
      .digest('hex');

    return hash === expectedHash;
  } catch {
    return false;
  }
}

export function getSessionId(request: any): string | null {
  const authUserId = (request as any).authUserId;
  if (authUserId) {
    return authUserId;
  }
  return null;
}
