const express = require('express');
const router = express.Router();
const { supabaseAdmin } = require('../config/supabase');
const { authenticateUser } = require('../middleware/auth');
const { validateRequest, schemas } = require('../middleware/validation');

// Get saved payment details
router.get('/saved', authenticateUser, async (req, res) => {
    try {
        const userId = req.user.id;

        const { data, error } = await supabaseAdmin
            .from('payments')
            .select('*')
            .eq('student_id', userId)
            .eq('is_default', true)
            .order('created_at', { ascending: false })
            .limit(1)
            .single();

        if (error && error.code !== 'PGRST116') { // PGRST116 = no rows returned
            throw error;
        }

        res.json({ success: true, payment: data || null });
    } catch (error) {
        console.error('Get payment details error:', error);
        res.status(500).json({ error: 'Failed to fetch payment details' });
    }
});

// Save payment details
router.post('/save', authenticateUser, validateRequest(schemas.savePayment), async (req, res) => {
    try {
        const userId = req.user.id;
        const { payment_method, name, mobile, upi_id, card_last4 } = req.body;

        // Mark all existing payments as non-default
        await supabaseAdmin
            .from('payments')
            .update({ is_default: false })
            .eq('student_id', userId);

        // Insert new payment details
        const { data, error } = await supabaseAdmin
            .from('payments')
            .insert({
                student_id: userId,
                payment_method,
                name,
                mobile,
                upi_id: upi_id || null,
                card_last4: card_last4 || null,
                is_default: true
            })
            .select()
            .single();

        if (error) throw error;

        res.json({ success: true, payment: data });
    } catch (error) {
        console.error('Save payment details error:', error);
        res.status(500).json({ error: 'Failed to save payment details' });
    }
});

// Process demo payment
router.post('/process', authenticateUser, async (req, res) => {
    try {
        const { order_id, payment_method, amount } = req.body;

        if (!order_id || !payment_method || !amount) {
            return res.status(400).json({ error: 'Missing required fields' });
        }

        // Simulate payment processing delay
        await new Promise(resolve => setTimeout(resolve, 1000));

        // In a real app, you would integrate with a payment gateway here
        // For demo, we'll just return success

        const paymentResult = {
            success: true,
            transaction_id: `TXN${Date.now()}${Math.floor(Math.random() * 1000)}`,
            payment_method,
            amount,
            timestamp: new Date().toISOString()
        };

        res.json({
            success: true,
            payment: paymentResult,
            message: 'Payment processed successfully (Demo Mode)'
        });
    } catch (error) {
        console.error('Process payment error:', error);
        res.status(500).json({ error: 'Payment processing failed' });
    }
});

// Update payment details
router.put('/saved', authenticateUser, validateRequest(schemas.savePayment), async (req, res) => {
    try {
        const userId = req.user.id;
        const { payment_method, name, mobile, upi_id, card_last4 } = req.body;

        // Get current default payment
        const { data: current } = await supabaseAdmin
            .from('payments')
            .select('id')
            .eq('student_id', userId)
            .eq('is_default', true)
            .single();

        if (current) {
            // Update existing
            const { data, error } = await supabaseAdmin
                .from('payments')
                .update({
                    payment_method,
                    name,
                    mobile,
                    upi_id: upi_id || null,
                    card_last4: card_last4 || null,
                    updated_at: new Date().toISOString()
                })
                .eq('id', current.id)
                .select()
                .single();

            if (error) throw error;

            res.json({ success: true, payment: data });
        } else {
            // Create new if none exists
            const { data, error } = await supabaseAdmin
                .from('payments')
                .insert({
                    student_id: userId,
                    payment_method,
                    name,
                    mobile,
                    upi_id: upi_id || null,
                    card_last4: card_last4 || null,
                    is_default: true
                })
                .select()
                .single();

            if (error) throw error;

            res.json({ success: true, payment: data });
        }
    } catch (error) {
        console.error('Update payment details error:', error);
        res.status(500).json({ error: 'Failed to update payment details' });
    }
});

module.exports = router;
