const db = require('../config/database');

const formatDateForDb = (date) => date.toISOString().split('T')[0];

const activateSubscription = async (subscriptionId, userId = null) => {
  const params = userId ? [subscriptionId, userId] : [subscriptionId];
  const userCondition = userId ? 'AND ds.user_id = ?' : '';

  const [rows] = await db.execute(
    `SELECT ds.id, ds.user_id, ds.plan_id, sp.duration_months
     FROM device_subscriptions ds
     JOIN subscription_plans sp ON ds.plan_id = sp.id
     WHERE ds.id = ? ${userCondition}
     LIMIT 1`,
    params
  );

  if (rows.length === 0) {
    throw new Error('Subscription not found or access denied');
  }

  const subscription = rows[0];
  const startDate = new Date();
  const endDate = new Date(startDate);
  endDate.setMonth(endDate.getMonth() + (subscription.duration_months || 1));

  await db.execute(
    `UPDATE device_subscriptions 
     SET status = 'active', start_date = ?, end_date = ?, updated_at = NOW()
     WHERE id = ?`,
    [formatDateForDb(startDate), formatDateForDb(endDate), subscriptionId]
  );

  return {
    id: subscriptionId,
    status: 'active',
    start_date: startDate.toISOString(),
    end_date: endDate.toISOString()
  };
};

module.exports = {
  activateSubscription
};
