/*
 *  author: Yagnik Poshiya
 *  organization: Webbrains Technologies Private Limited
 */

import { getSupabaseServiceRoleClient } from '@/lib/supabase/service-role';

export type ChatRateLimitResult =
  | { allowed: true }
  | { allowed: false; retryAfterSeconds: number; maxRequests: number; window: string };

/**
 * The visitor's IP as seen by the platform edge. DigitalOcean App Platform sets
 * `do-connecting-ip`; elsewhere the first `x-forwarded-for` hop is the client.
 */
export function clientIpFromHeaders(headers: Headers): string | null {
  const doIp = headers.get('do-connecting-ip')?.trim();
  if (doIp) return doIp;
  const forwarded = headers.get('x-forwarded-for')?.split(',')[0]?.trim();
  if (forwarded) return forwarded;
  return headers.get('x-real-ip')?.trim() || null;
}

/**
 * Counts one chat message against the project agent's per-visitor rate limit
 * (public.consume_chat_rate_limit: N per second/minute per visitor id, 5×N per IP).
 * Fails open: a limiter outage must not take every chat down with it.
 */
export async function consumeChatRateLimit(input: {
  projectAgentId: string;
  visitorId: string;
  ip: string | null;
}): Promise<ChatRateLimitResult> {
  if (!input.projectAgentId || !input.visitorId) return { allowed: true };
  const { data, error } = await getSupabaseServiceRoleClient().rpc('consume_chat_rate_limit', {
    p_project_agent_id: input.projectAgentId,
    p_visitor_id: input.visitorId,
    p_ip: input.ip ?? '',
  });
  if (error) {
    console.error('[public-rag] rate limit check failed; allowing request', error.message);
    return { allowed: true };
  }
  const row = (Array.isArray(data) ? data[0] : data) as
    | { allowed?: boolean; retry_after_seconds?: number; max_requests?: number; window_name?: string }
    | undefined;
  if (!row || row.allowed !== false) return { allowed: true };
  return {
    allowed: false,
    retryAfterSeconds: Math.max(1, Number(row.retry_after_seconds ?? 1)),
    maxRequests: Number(row.max_requests ?? 0),
    window: String(row.window_name ?? ''),
  };
}
