import rateLimit from 'express-rate-limit';
import { supabase } from './supabase.js';
import { logger } from './logger.js';

const LICENCE_WINDOW_MS    = 60 * 60 * 1000;
const LICENCE_MAX_PER_HOUR = 20;

export const ipLimiter = rateLimit({
  windowMs:        60 * 1000,
  max:             10,
  standardHeaders: true,
  legacyHeaders:   false,
  message:         { error: 'rate_limit_ip' },
});

export async function licenceLimiter(licenceId: string): Promise<boolean> {
  const windowStart = new Date(Date.now() - LICENCE_WINDOW_MS).toISOString();

  const { count, error } = await supabase
    .from('usage_logs')
    .select('*', { count: 'exact', head: true })
    .eq('licence_id', licenceId)
    .gte('created_at', windowStart);

  if (error) {
    // Fail open on DB error — the monthly quota is the primary guard
    logger.warn('licenceLimiter: DB error, failing open', { err: error.message });
    return true;
  }

  return (count ?? 0) < LICENCE_MAX_PER_HOUR;
}
