import { timingSafeEqual } from 'node:crypto';
import type { IncomingHttpHeaders } from 'node:http';
import { fromNodeHeaders } from 'better-auth/node';

export interface SocketSessionResult {
  session: unknown;
  user: { id: string };
}

export interface SessionAuth {
  api: {
    getSession(context: { headers: Headers }): Promise<SocketSessionResult | null>;
  };
}

export function validateDiscordServiceToken(
  candidate: unknown,
  expected: string | undefined,
): boolean {
  if (typeof candidate !== 'string' || !expected) return false;
  const candidateBuffer = Buffer.from(candidate);
  const expectedBuffer = Buffer.from(expected);
  return (
    candidateBuffer.length === expectedBuffer.length &&
    timingSafeEqual(candidateBuffer, expectedBuffer)
  );
}

export async function validateSocketSession(
  headers: IncomingHttpHeaders,
  auth: SessionAuth,
): Promise<SocketSessionResult | null> {
  const sessionHeaders = fromNodeHeaders(headers);
  const result = await auth.api.getSession({ headers: sessionHeaders });

  if (!result) {
    return null;
  }

  return {
    session: result.session,
    user: { id: result.user.id },
  };
}
