/**
 * models/usageLog.js
 * Tracks monthly usage per user, reset on billing cycle.
 */

'use strict';

const { db } = require('../config/db');

const upsert = db.prepare(`
  INSERT INTO usage_log (user_id, resource, period_start, count)
  VALUES (?, ?, ?, 1)
  ON CONFLICT(user_id, resource, period_start) DO UPDATE SET count = count + 1
`);

const get = db.prepare(`
  SELECT * FROM usage_log WHERE user_id = ? AND resource = ? AND period_start = ?
`);

function periodStart(timestamp = Date.now()) {
  // Calendar month, UTC. We can switch to billing-cycle based per user later.
  const d = new Date(timestamp);
  return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1);
}

function increment(userId, resource, timestamp = Date.now()) {
  upsert.run(userId, resource, periodStart(timestamp));
}

function current(userId, resource, timestamp = Date.now()) {
  const row = get.get(userId, resource, periodStart(timestamp));
  return row ? row.count : 0;
}

function forUser(userId, timestamp = Date.now()) {
  const start = periodStart(timestamp);
  return {
    period_start: start,
    scans:    current(userId, 'scan',    timestamp),
    takedowns:current(userId, 'takedown',timestamp),
    cases:    current(userId, 'case',    timestamp),
  };
}

module.exports = { increment, current, forUser, periodStart };
