import { Router, Request, Response } from 'express';
import { authMiddleware, AuthRequest } from '../middleware/auth';
import { createCheckoutSession, createPortalSession, handleWebhook } from '../services/stripe';

const router = Router();

const BASE_URL = process.env.BASE_URL || 'https://sportsclaw.guru';

// Create checkout session
router.post('/checkout', authMiddleware, async (req: AuthRequest, res: Response) => {
  try {
    const { plan } = req.body;
    
    if (!plan || !['weekly', 'monthly'].includes(plan)) {
      return res.status(400).json({ error: 'Invalid plan' });
    }
    
    const checkoutUrl = await createCheckoutSession(
      req.userId!,
      req.user.email,
      plan,
      `${BASE_URL}/dashboard?success=true`,
      `${BASE_URL}/signup?canceled=true`
    );
    
    res.json({ url: checkoutUrl });
  } catch (error) {
    console.error('Checkout error:', error);
    res.status(500).json({ error: 'Failed to create checkout session' });
  }
});

// Customer portal
router.post('/portal', authMiddleware, async (req: AuthRequest, res: Response) => {
  try {
    if (!req.user.stripe_customer_id) {
      return res.status(400).json({ error: 'No active subscription' });
    }
    
    const portalUrl = await createPortalSession(
      req.user.stripe_customer_id,
      `${BASE_URL}/dashboard`
    );
    
    res.json({ url: portalUrl });
  } catch (error) {
    console.error('Portal error:', error);
    res.status(500).json({ error: 'Failed to create portal session' });
  }
});

// Stripe webhook
router.post('/webhook', async (req: Request, res: Response) => {
  const signature = req.headers['stripe-signature'] as string;
  
  try {
    await handleWebhook(req.body, signature);
    res.json({ received: true });
  } catch (error) {
    console.error('Webhook error:', error);
    res.status(400).json({ error: 'Webhook failed' });
  }
});

export default router;
