import { query } from '../db';

const DAILY_LIMITS: Record<string, number> = {
  free: 10,
  weekly: -1,  // unlimited
  monthly: -1, // unlimited
};

export async function recordUsage(
  userId: string,
  queryType: string,
  queryText: string,
  responseTimeMs: number
): Promise<void> {
  // Record individual query
  await query(
    `INSERT INTO sc_usage (user_id, query_type, query_text, response_time_ms)
     VALUES ($1, $2, $3, $4)`,
    [userId, queryType, queryText, responseTimeMs]
  );
  
  // Update daily counter
  const today = new Date().toISOString().split('T')[0];
  await query(
    `INSERT INTO sc_daily_usage (user_id, date, query_count)
     VALUES ($1, $2, 1)
     ON CONFLICT (user_id, date)
     DO UPDATE SET query_count = sc_daily_usage.query_count + 1`,
    [userId, today]
  );
}

export async function getDailyUsage(userId: string): Promise<number> {
  const today = new Date().toISOString().split('T')[0];
  const result = await query(
    'SELECT query_count FROM sc_daily_usage WHERE user_id = $1 AND date = $2',
    [userId, today]
  );
  return result.rows[0]?.query_count || 0;
}

export async function canMakeQuery(userId: string, _plan?: string): Promise<{ allowed: boolean; remaining: number; limit: number }> {
  // Always verify plan from database, never trust client-provided value
  const userResult = await query('SELECT plan FROM sc_users WHERE id = $1', [userId]);
  const dbPlan = userResult.rows[0]?.plan || 'free';
  const limit = DAILY_LIMITS[dbPlan] || 10;
  
  // Unlimited for paid plans
  if (limit === -1) {
    return { allowed: true, remaining: -1, limit: -1 };
  }
  
  const used = await getDailyUsage(userId);
  const remaining = Math.max(0, limit - used);
  
  return {
    allowed: used < limit,
    remaining,
    limit,
  };
}

export async function getUsageStats(userId: string, days: number = 7): Promise<any[]> {
  const result = await query(
    `SELECT date, query_count 
     FROM sc_daily_usage 
     WHERE user_id = $1 AND date >= CURRENT_DATE - INTERVAL '1 day' * $2
     ORDER BY date DESC`,
    [userId, days]
  );
  return result.rows;
}
