// backend/src/utils/limits.js
// Shared pipeline usage-limit logic used by both /pipeline/run and /niche/run-with-topics

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

const DAILY_RUN_LIMITS = { starter: 1, pro: 3, agency: 10 };

/**
 * Checks whether a user can start a new pipeline run.
 * Returns { allowed: boolean, reason?, status?, payload? }
 */
export async function checkPipelineAllowed(userId) {
  // 1. Already running?
  const { rows: running } = await query(
    "SELECT id FROM pipeline_runs WHERE user_id = $1 AND status IN ('queued','running') LIMIT 1",
    [userId]
  );
  if (running[0]) {
    return {
      allowed: false,
      status: 409,
      payload: { error: 'pipeline_running', message: 'A pipeline is already running' }
    };
  }

  // 2. Daily limit by plan
  const { rows: planRows } = await query(
    `SELECT p.id as plan_id FROM users u LEFT JOIN plans p ON u.plan_id = p.id WHERE u.id = $1`,
    [userId]
  );
  const planId = planRows[0]?.plan_id || 'starter';
  const limit = DAILY_RUN_LIMITS[planId] || 1;

  const { rows: todayRuns } = await query(
    `SELECT COUNT(*)::int as count FROM pipeline_runs
     WHERE user_id = $1 AND DATE(created_at) = CURRENT_DATE AND status != 'failed'`,
    [userId]
  );
  const used = todayRuns[0].count;

  if (used >= limit) {
    return {
      allowed: false,
      status: 429,
      payload: {
        error: 'daily_limit_reached',
        message: `Your ${planId} plan allows ${limit} pipeline run${limit > 1 ? 's' : ''} per day. Upgrade for more.`,
        limit,
        used
      }
    };
  }

  return { allowed: true, limit, used, remaining: limit - used - 1 };
}
