const db = require('../db/models');

async function recordFirstActivationEvent(eventType, actorId) {
  const existing = await db.coaching_audit_events.findOne({
    where: { event_type: eventType, actorId },
    attributes: ['id'],
  });

  if (existing) {
    return false;
  }

  await db.coaching_audit_events.create({
    event_type: eventType,
    actorId,
    target_type: 'workspace',
    target_id: null,
    metadata: {},
  });
  return true;
}

async function recordLoginActivation(user) {
  const accountAgeMs = Date.now() - new Date(user.createdAt).getTime();
  if (accountAgeMs >= 7 * 24 * 60 * 60 * 1000) {
    await recordFirstActivationEvent('week_1_active', user.id);
  }
  if (accountAgeMs >= 28 * 24 * 60 * 60 * 1000) {
    await recordFirstActivationEvent('week_4_active', user.id);
  }
}

module.exports = { recordFirstActivationEvent, recordLoginActivation };
