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

// Student registration/login
router.post('/register', validateRequest(schemas.registerStudent), async (req, res) => {
    try {
        const { student_id, name, email, mobile } = req.body;

        // Check if student already exists
        const { data: existing } = await supabaseAdmin
            .from('users')
            .select('*')
            .eq('student_id', student_id)
            .single();

        if (existing) {
            return res.status(400).json({ error: 'Student ID already registered' });
        }

        // Create user in database
        const { data: user, error } = await supabaseAdmin
            .from('users')
            .insert({
                student_id,
                name,
                email,
                mobile,
                role: 'student'
            })
            .select()
            .single();

        if (error) {
            throw error;
        }

        res.json({
            success: true,
            user: {
                id: user.id,
                student_id: user.student_id,
                name: user.name,
                role: user.role
            }
        });
    } catch (error) {
        console.error('Registration error:', error);
        res.status(500).json({ error: 'Registration failed', details: error.message });
    }
});

// Login with student ID (Simplified - No Supabase Auth required)
router.post('/login', async (req, res) => {
    try {
        const { student_id } = req.body;

        if (!student_id) {
            return res.status(400).json({ error: 'Student ID is required' });
        }

        // Find user
        const { data: user, error } = await supabaseAdmin
            .from('users')
            .select('*')
            .eq('student_id', student_id)
            .single();

        if (error || !user) {
            return res.status(404).json({ error: 'Student not found' });
        }

        // Generate a simple session token (demo purposes)
        // In production, use proper JWT with secret key
        const sessionToken = Buffer.from(JSON.stringify({
            userId: user.id,
            studentId: user.student_id,
            role: user.role,
            timestamp: Date.now()
        })).toString('base64');

        res.json({
            success: true,
            user: {
                id: user.id,
                student_id: user.student_id,
                name: user.name,
                email: user.email,
                mobile: user.mobile,
                role: user.role
            },
            token: sessionToken
        });
    } catch (error) {
        console.error('Login error:', error);
        res.status(500).json({ error: 'Login failed', details: error.message });
    }
});

// Verify token (Simplified)
router.post('/verify', async (req, res) => {
    try {
        const { token } = req.body;

        if (!token) {
            return res.status(400).json({ error: 'Token is required' });
        }

        // Decode token
        const decoded = JSON.parse(Buffer.from(token, 'base64').toString());

        // Get user details from database
        const { data: userData } = await supabaseAdmin
            .from('users')
            .select('*')
            .eq('id', decoded.userId)
            .single();

        if (!userData) {
            return res.status(401).json({ error: 'Invalid token' });
        }

        res.json({
            success: true,
            user: userData
        });
    } catch (error) {
        console.error('Verification error:', error);
        res.status(401).json({ error: 'Invalid token' });
    }
});

// Logout
router.post('/logout', async (req, res) => {
    res.json({ success: true });
});

module.exports = router;
