import { createHmac } from 'crypto';
import { db } from '@server/db/drizzle';
import { sql } from 'drizzle-orm';

export function validateTwilioSignature(
  authToken: string,
  signature: string,
  url: string,
  params: Record<string, string>
): boolean {
  const sortedKeys = Object.keys(params).sort();
  let data = url;
  for (const key of sortedKeys) {
    data += key + params[key];
  }

  const computed = createHmac('sha1', authToken)
    .update(Buffer.from(data, 'utf-8'))
    .digest('base64');

  return computed === signature;
}

export async function getTwilioAuthToken(restaurantId: string | null): Promise<string | null> {
  if (!restaurantId) return process.env.TWILIO_AUTH_TOKEN || null;

  try {
    const { decrypt } = await import('@server/utils/crypto');
    /* raw: SELECT twilio_auth_token, twilio_connected FROM telephone_settings WHERE restaurant_id = $1 */
    const row = await db.execute(sql`SELECT twilio_auth_token, twilio_connected FROM telephone_settings WHERE restaurant_id = ${restaurantId}`);
    const r = row.rows[0] as Record<string, unknown> | undefined;
    if (row.rows.length > 0 && r?.twilio_connected && r?.twilio_auth_token) {
      return decrypt(r.twilio_auth_token as string);
    }
  } catch (err: unknown) {
    console.warn(`[Twilio] Failed to fetch auth token: ${err instanceof Error ? err.message : String(err)}`);
  }

  return process.env.TWILIO_AUTH_TOKEN || null;
}
