/**
 * services/trial-license-email.js — free 30-day self-hosted license key email.
 *
 * Owns: delivering a newly minted free trial key to the user who requested it.
 * Does NOT own: minting (routes/license.js), payments, plan credits.
 *
 * Separate from services/welcome-email.js on purpose: that one is post-PAYMENT
 * shaped — it renders a payment ID, an amount, "your plan is now active", and
 * states "Same key works forever — no expiry". All four are wrong for a 30-day
 * trial, and the expiry claim is the opposite of the truth.
 *
 * Same contract as welcome-email.js: fires via Resend (RESEND_API_KEY), retries
 * once, returns { sent, error }, never throws. Callers treat failure as
 * non-fatal — the key is already minted and shown on-screen.
 */

'use strict';

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

const APP_URL        = process.env.APP_URL || 'https://tunevault.app';
const RESEND_API_KEY = process.env.RESEND_API_KEY;
const FROM_ADDRESS   = process.env.EMAIL_FROM || 'TuneVault <noreply@tunevault.app>';
const RESEND_API_URL = 'https://api.resend.com';

function buildHtml({ userName, licenseKey, expiresAt }) {
  const firstName = userName ? userName.split(' ')[0] : 'there';
  const expiryStr = expiresAt
    ? new Date(expiresAt).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' })
    : '30 days from today';

  return `<!DOCTYPE html>
<html>
<body style="margin:0;padding:0;background:#0a0a0c;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#0a0a0c;padding:32px 16px;">
    <tr><td align="center">
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:560px;background:#111114;border:1px solid #2a2a30;border-radius:14px;">
        <tr><td style="padding:32px 32px 8px;">
          <div style="color:#f0a830;font-size:11px;letter-spacing:2px;text-transform:uppercase;font-family:monospace;">TuneVault Self-Hosted</div>
          <h1 style="color:#e8e8ed;font-size:24px;margin:12px 0 0;">Your free 30-day license key</h1>
          <p style="color:#b8b8c8;font-size:15px;line-height:1.6;margin:14px 0 0;">
            Hi ${firstName}, here's your key. It runs TuneVault entirely on your own infrastructure — no data leaves your network.
          </p>
        </td></tr>

        <tr><td style="padding:20px 32px 0;">
          <div style="background:#0d0d10;border:1px solid #2a2a30;border-radius:10px;padding:16px;text-align:center;">
            <div style="color:#6a6a76;font-size:11px;letter-spacing:1px;text-transform:uppercase;font-family:monospace;margin-bottom:8px;">Your license key</div>
            <span style="font-size:15px;color:#f0a830;font-family:monospace;letter-spacing:0.5px;word-break:break-all;">${licenseKey}</span>
          </div>
        </td></tr>

        <tr><td style="padding:20px 32px 0;">
          <div style="color:#e8e8ed;font-size:14px;font-weight:600;margin-bottom:8px;">Get running</div>
          <div style="color:#b8b8c8;font-size:14px;line-height:1.9;">
            1. Download: <a href="${APP_URL}/download" style="color:#f0a830;">${APP_URL}/download</a><br>
            2. Set <span style="color:#e8e8ed;font-family:monospace;">TUNEVAULT_LICENSE_KEY=${licenseKey}</span> in <span style="color:#e8e8ed;font-family:monospace;">.env</span><br>
            3. Run: <span style="color:#e8e8ed;font-family:monospace;">bash setup.sh</span>
          </div>
        </td></tr>

        <tr><td style="padding:20px 32px 0;">
          <div style="background:rgba(52,211,153,0.08);border:1px solid rgba(52,211,153,0.2);border-radius:10px;padding:14px 16px;">
            <div style="color:#34d399;font-size:13px;line-height:1.7;">
              <strong>What's included:</strong> ${FREE_TIER.max_connections} connection &middot; unlimited health checks &middot; the full 200+ check catalog.<br>
              <strong>Valid until ${expiryStr}.</strong> After that, existing connections and reports stay readable, but new health checks stop until you renew.
            </div>
          </div>
        </td></tr>

        <tr><td style="padding:24px 32px 32px;">
          <p style="color:#6a6a76;font-size:13px;line-height:1.6;margin:0;">
            Need more connections or a longer term? <a href="${APP_URL}/pricing" style="color:#f0a830;">See pricing</a>.
            Questions? Just reply to this email.
          </p>
        </td></tr>
      </table>
    </td></tr>
  </table>
</body>
</html>`;
}

/**
 * Sends the free trial license key. Retries once on failure.
 * Returns { sent: true } on success, { sent: false, error } otherwise. Never throws.
 */
async function sendTrialLicenseEmail({ userEmail, userName, licenseKey, expiresAt }) {
  if (!RESEND_API_KEY) {
    console.warn('[trial-license-email] RESEND_API_KEY not set — skipping for', userEmail);
    return { sent: false, error: 'RESEND_API_KEY not configured' };
  }

  const expiryStr = expiresAt
    ? new Date(expiresAt).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' })
    : '30 days from today';
  const subject = 'Your free 30-day TuneVault Self-Hosted license key';

  const plainText = `Hi ${userName || 'there'},

Here's your free 30-day TuneVault Self-Hosted license key.

Your License Key
────────────────
${licenseKey}

Get running:
1. Download: ${APP_URL}/download
2. Set TUNEVAULT_LICENSE_KEY=${licenseKey} in .env
3. Run: bash setup.sh

What's included: ${FREE_TIER.max_connections} connection, unlimited health checks, the full 200+ check catalog.
Valid until ${expiryStr}. After that, existing connections and reports stay readable, but new health checks stop until you renew.

Need more connections or a longer term? ${APP_URL}/pricing

Questions? Reply to this email.

TuneVault`;

  const html = buildHtml({ userName, licenseKey, expiresAt });

  for (let attempt = 1; attempt <= 2; attempt++) {
    try {
      const res = await fetch(`${RESEND_API_URL}/emails`, {
        method : 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${RESEND_API_KEY}` },
        body   : JSON.stringify({ from: FROM_ADDRESS, to: userEmail, subject, text: plainText, html })
      });

      if (res.ok) {
        console.log(`[trial-license-email] sent to ${userEmail} (attempt: ${attempt})`);
        return { sent: true };
      }

      const errBody = await res.text().catch(() => '');
      const errMsg  = `HTTP ${res.status}: ${errBody}`;
      console.warn(`[trial-license-email] attempt ${attempt} failed for ${userEmail}: ${errMsg}`);
      if (attempt === 2) return { sent: false, error: errMsg };
      await new Promise(r => setTimeout(r, 1500));
    } catch (err) {
      console.warn(`[trial-license-email] attempt ${attempt} threw for ${userEmail}: ${err.message}`);
      if (attempt === 2) return { sent: false, error: err.message };
      await new Promise(r => setTimeout(r, 1500));
    }
  }

  return { sent: false, error: 'Unknown failure' };
}

module.exports = { sendTrialLicenseEmail };
