import { Controller, Get, Post } from '@overnightjs/core';
import { Request, Response } from 'express';
import PaymentService from '../services/PaymentService';

@Controller('api/payments')
export class PaymentController {

    /**
     * Create a Stripe Checkout Session
     * POST /api/payments/checkout
     */
    @Post('checkout')
    async createCheckout(req: Request, res: Response): Promise<void> {
        try {
            const { userId, planId, currency = 'usd' } = req.body;

            if (!userId || !planId) {
                res.status(400).json({
                    success: false,
                    error: 'Missing required fields: userId, planId'
                });
                return;
            }

            const result = await PaymentService.createCheckoutWithPlan({
                userId,
                planId,
                currency
            });

            res.status(200).json({
                success: true,
                data: result
            });
        } catch (error: any) {
            const statusCode = error.message.includes('not found') ? 404 : 500;
            res.status(statusCode).json({
                success: false,
                error: error.message || 'Internal server error'
            });
        }
    }

    /**
     * Handle Stripe Webhook
     * POST /api/payments/webhook
     * Note: This requires the raw body for signature verification
     */
    @Post('webhook')
    async handleWebhook(req: Request, res: Response): Promise<void> {
        try {
            const signature = req.headers['stripe-signature'] as string;

            if (!signature) {
                res.status(400).json({
                    success: false,
                    error: 'Missing stripe-signature header'
                });
                return;
            }

            // We expect rawBody to be attached to req via middleware in index.ts
            const rawBody = (req as any).rawBody;

            if (!rawBody) {
                console.error('Raw body not found. Ensure raw body middleware is configured for webhooks.');
                res.status(400).json({
                    success: false,
                    error: 'Raw body missing'
                });
                return;
            }

            const result = await PaymentService.handleWebhook(rawBody, signature);

            res.status(200).json(result);
        } catch (error: any) {
            console.error('Webhook error:', error);
            res.status(400).json({
                success: false,
                error: `Webhook Error: ${error.message}`
            });
        }
    }

    /**
     * Verify Payment Status (for redirection page)
     * GET /api/payments/verify/:sessionId
     */
    @Get('verify/:sessionId')
    async verifyPayment(req: Request, res: Response): Promise<void> {
        try {
            const { sessionId } = req.params;
            if (!sessionId) {
                res.status(400).json({ success: false, error: 'Session ID is required' });
                return;
            }

            const result = await PaymentService.verifyAndFulfillSession(sessionId);
            res.status(200).json({
                success: true,
                status: result.status,
                subscription: result.subscription
            });
        } catch (error: any) {
            console.error('Verification error:', error);
            res.status(500).json({
                success: false,
                error: error.message || 'Internal server error'
            });
        }
    }
}
