import express from 'express';
import { config } from './config.js';
import { getPlan, listPlans, PREMIUM_FEATURES } from './plans.js';
import { getStripe } from './stripe.js';
import { getStoreSnapshot, upsertCustomer, upsertSubscription, findLicenseByCustomerId } from './store.js';
import {
  syncLicenseFromSubscription,
  grantOneTimeLicense,
  validateLicense,
  deactivateLicense
} from './licenseLogic.js';

const app = express();
app.use('/api/stripe/webhook', express.raw({ type: 'application/json' }));
app.use(express.json());

app.get('/health', (_req, res) => {
  res.json({ ok: true, service: 'dashcaddy-license-server' });
});

app.get('/api/public/config', (_req, res) => {
  res.json({
    ok: true,
    publishableKey: config.stripePublishableKey || null,
    websiteUrl: config.websiteUrl
  });
});

app.get('/api/public/plans', (_req, res) => {
  res.json({ ok: true, tier: 'premium', features: PREMIUM_FEATURES, plans: listPlans() });
});

app.get('/api/admin/debug/store', (_req, res) => {
  res.json({ ok: true, store: getStoreSnapshot() });
});

/**
 * Subscription checkout. Customer subscribes and is auto-renewed on the
 * plan's interval. The license is created on the first webhook event and
 * extended on every renewal.
 */
app.post('/api/checkout/subscription', async (req, res) => {
  try {
    const { planCode, customerEmail } = req.body || {};
    const plan = getPlan(planCode);
    if (!plan) return res.status(400).json({ ok: false, error: 'Invalid planCode' });

    const stripe = getStripe();
    const session = await stripe.checkout.sessions.create({
      mode: 'subscription',
      payment_method_types: ['card'],
      line_items: [{
        price_data: {
          currency: 'usd',
          product_data: { name: plan.label, description: 'DashCaddy Premium subscription' },
          recurring: { interval: plan.interval, interval_count: plan.intervalCount },
          unit_amount: plan.amountUsd * 100
        },
        quantity: 1
      }],
      success_url: `${config.websiteUrl}/success?session_id={CHECKOUT_SESSION_ID}&tier=premium`,
      cancel_url: `${config.websiteUrl}/pricing`,
      allow_promotion_codes: true,
      billing_address_collection: 'required',
      customer_email: customerEmail || undefined,
      metadata: {
        source: 'dashcaddy.net',
        planCode: plan.code,
        tier: plan.tier,
        mode: 'subscription',
        // Bake the email into session metadata so the webhook can find
        // the existing license without a Stripe API call.
        customerEmail: customerEmail || ''
      },
      subscription_data: {
        metadata: {
          source: 'dashcaddy.net',
          planCode: plan.code,
          tier: plan.tier,
          customerEmail: customerEmail || ''
        }
      }
    });

    return res.json({ ok: true, url: session.url, sessionId: session.id });
  } catch (error) {
    console.error('Subscription checkout error:', error);
    return res.status(500).json({ ok: false, error: error.message || 'Checkout failed' });
  }
});

/**
 * One-time purchase checkout. Customer pays once for a license of the
 * plan duration. If they buy again, time is added to their existing license.
 */
app.post('/api/checkout/one-time', async (req, res) => {
  try {
    const { planCode, customerEmail } = req.body || {};
    const plan = getPlan(planCode);
    if (!plan) return res.status(400).json({ ok: false, error: 'Invalid planCode' });

    const stripe = getStripe();
    const session = await stripe.checkout.sessions.create({
      mode: 'payment',
      payment_method_types: ['card'],
      line_items: [{
        price_data: {
          currency: 'usd',
          product_data: { name: plan.label, description: 'DashCaddy Premium one-time license' },
          unit_amount: plan.amountUsd * 100
        },
        quantity: 1
      }],
      success_url: `${config.websiteUrl}/success?session_id={CHECKOUT_SESSION_ID}&tier=premium`,
      cancel_url: `${config.websiteUrl}/pricing`,
      allow_promotion_codes: true,
      billing_address_collection: 'required',
      customer_email: customerEmail || undefined,
      metadata: {
        source: 'dashcaddy.net',
        planCode: plan.code,
        tier: plan.tier,
        mode: 'one-time',
        durationDays: String(plan.durationDays),
        customerEmail: customerEmail || ''
      },
      payment_intent_data: {
        metadata: {
          source: 'dashcaddy.net',
          planCode: plan.code,
          tier: plan.tier,
          mode: 'one-time',
          durationDays: String(plan.durationDays),
          customerEmail: customerEmail || ''
        }
      }
    });

    return res.json({ ok: true, url: session.url, sessionId: session.id });
  } catch (error) {
    console.error('One-time checkout error:', error);
    return res.status(500).json({ ok: false, error: error.message || 'Checkout failed' });
  }
});

/**
 * Look up an existing license for a customer. Tries customerId first,
 * then falls back to email. Returns null if no active license exists.
 */
function findCustomersLicense(customerId, customerEmail) {
  if (customerId) {
    const byCustomer = findLicenseByCustomerId(customerId);
    if (byCustomer) return byCustomer;
  }
  if (customerEmail) {
    const { findActiveLicenseByCustomerEmail } = require('./store.js');
    const byEmail = findActiveLicenseByCustomerEmail(customerEmail);
    if (byEmail) return byEmail;
  }
  return null;
}

/**
 * Stripe webhook endpoint. Handles subscription lifecycle events AND
 * one-time payment completion events. The same handler routes based on
 * event type and updates the customer's license accordingly.
 */
app.post('/api/stripe/webhook', async (req, res) => {
  try {
    if (!config.stripeWebhookSecret) {
      return res.status(500).json({ ok: false, error: 'Missing STRIPE_WEBHOOK_SECRET' });
    }

    const signature = req.headers['stripe-signature'];
    if (!signature) {
      return res.status(400).json({ ok: false, error: 'Missing stripe-signature header' });
    }

    const stripe = getStripe();
    const event = stripe.webhooks.constructEvent(req.body, signature, config.stripeWebhookSecret);

    switch (event.type) {
      case 'checkout.session.completed': {
        const session = event.data.object;
        const planCode = session.metadata?.planCode;
        const mode = session.metadata?.mode || 'subscription';
        const customerId = typeof session.customer === 'string' ? session.customer : session.customer?.id;
        // Email resolution: session metadata (baked at creation) > session.customer_email > session.customer_details.email
        const customerEmail = session.metadata?.customerEmail || session.customer_email || session.customer_details?.email || null;

        if (customerId) {
          upsertCustomer({ id: String(customerId), email: customerEmail, checkoutSessionId: session.id });
        }

        // For one-time payments, generate the license on checkout.session.completed
        if (mode === 'one-time' && planCode) {
          const plan = getPlan(planCode);
          if (plan) {
            const license = grantOneTimeLicense({
              paymentIntentId: typeof session.payment_intent === 'string' ? session.payment_intent : session.payment_intent?.id,
              customerId,
              customerEmail,
              planCode,
              durationDays: plan.durationDays
            });
            console.log('One-time license granted', {
              sessionId: session.id,
              licenseKey: license.key,
              customerEmail,
              extended: license.extended || false,
              addedDays: license.addedDays || plan.durationDays
            });
          }
        }
        break;
      }

      case 'customer.subscription.created':
      case 'customer.subscription.updated': {
        const subscription = event.data.object;
        const customerId = typeof subscription.customer === 'string' ? subscription.customer : subscription.customer?.id;
        // Email resolution: subscription metadata (baked at creation) > fetch from Stripe if missing
        let customerEmail = subscription.metadata?.customerEmail || null;
        if (!customerEmail && customerId) {
          try {
            const customer = await stripe.customers.retrieve(customerId);
            customerEmail = customer.email || null;
          } catch (err) {
            console.warn('Failed to fetch customer email', { customerId, error: err.message });
          }
        }
        const planCode = subscription.metadata?.planCode || 'premium_30d';
        const currentPeriodEnd = subscription.current_period_end
          ? new Date(subscription.current_period_end * 1000).toISOString()
          : null;

        upsertSubscription({
          id: subscription.id,
          customerId,
          status: subscription.status,
          planCode,
          currentPeriodEnd,
          cancelAtPeriodEnd: Boolean(subscription.cancel_at_period_end)
        });

        const license = syncLicenseFromSubscription({
          subscriptionId: subscription.id,
          customerId,
          customerEmail,
          planCode,
          status: subscription.status,
          currentPeriodEnd
        });

        console.log('Subscription license synced', {
          subscriptionId: subscription.id,
          licenseKey: license.key,
          status: license.status,
          expiresAt: license.expiresAt,
          customerEmail
        });
        break;
      }

      case 'customer.subscription.deleted': {
        const subscription = event.data.object;
        // Mark the subscription cancelled. License remains active until
        // currentPeriodEnd (Stripe handles non-renewal automatically).
        upsertSubscription({
          id: subscription.id,
          status: 'canceled',
          cancelAtPeriodEnd: true
        });
        console.log('Subscription cancelled', { subscriptionId: subscription.id });
        break;
      }

      case 'invoice.payment_failed': {
        const invoice = event.data.object;
        console.warn('Payment failed', { invoiceId: invoice.id, customerId: invoice.customer });
        break;
      }

      default:
        console.log('Unhandled Stripe event', event.type);
    }

    return res.json({ ok: true });
  } catch (error) {
    console.error('Webhook processing error:', error);
    return res.status(400).json({ ok: false, error: error.message || 'Webhook failed' });
  }
});

app.post('/api/license/validate', async (req, res) => {
  const { code, machine } = req.body || {};
  if (!code) return res.status(400).json({ ok: false, error: 'License code is required' });
  const result = validateLicense({ code, machine });
  return res.status(result.success ? 200 : 400).json(result);
});

app.post('/api/license/deactivate', async (req, res) => {
  const { code, machine } = req.body || {};
  if (!code) return res.status(400).json({ ok: false, error: 'License code is required' });
  const result = deactivateLicense({ code, machine });
  return res.status(result.success ? 200 : 400).json(result);
});

app.listen(config.port, () => {
  console.log(`dashcaddy-license-server listening on :${config.port}`);
});
