import { getPool } from '../db.js';
import { PLANS, type PlanKey } from './plans.js';

export async function recordUsage(
  customerId: string,
  platform: string,
  action: string
): Promise<void> {
  await getPool().query(
    'INSERT INTO usage_logs (customer_id, platform, action) VALUES (?, ?, ?)',
    [customerId, platform, action]
  );
}

export async function getMonthlyUsage(customerId: string): Promise<number> {
  const [rows] = await getPool().query<any[]>(
    `SELECT COUNT(*) as count FROM usage_logs
     WHERE customer_id = ?
       AND created_at >= DATE_FORMAT(NOW(), '%Y-%m-01')
       AND created_at < DATE_FORMAT(DATE_ADD(NOW(), INTERVAL 1 MONTH), '%Y-%m-01')`,
    [customerId]
  );
  return rows[0]?.count ?? 0;
}

export async function getUsageBreakdown(customerId: string): Promise<Record<string, number>> {
  const [rows] = await getPool().query<any[]>(
    `SELECT platform, COUNT(*) as count FROM usage_logs
     WHERE customer_id = ?
       AND created_at >= DATE_FORMAT(NOW(), '%Y-%m-01')
     GROUP BY platform`,
    [customerId]
  );
  const breakdown: Record<string, number> = {};
  for (const row of rows) {
    breakdown[row.platform] = row.count;
  }
  return breakdown;
}

export async function checkLimit(customerId: string, plan: PlanKey): Promise<{ allowed: boolean; limit: number; used: number }> {
  const planConfig = PLANS[plan];
  if (planConfig.monthlyCallLimit === -1) {
    return { allowed: true, limit: -1, used: 0 };
  }
  const used = await getMonthlyUsage(customerId);
  return { allowed: used < planConfig.monthlyCallLimit, limit: planConfig.monthlyCallLimit, used };
}
