const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { decryptPassword } = require('../utils/crypto');
const db = require('../config/database');
const router = express.Router();

// Test admin user creation
router.post('/admin/create-test-user', async (req, res) => {
  try {
    const hashedPassword = await bcrypt.hash('admin123', 10);
    
    await db.execute(`
      INSERT INTO users (email, password_hash, first_name, last_name, user_type, status)
      VALUES (?, ?, ?, ?, ?, ?)
      ON DUPLICATE KEY UPDATE password_hash = VALUES(password_hash)
    `, ['admin@gpstracking.com', hashedPassword, 'Super', 'Admin', 'admin', 'active']);
    
    res.json({ message: 'Test admin user created' });
  } catch (error) {
    res.status(500).json({ message: 'Server error: ' + error.message });
  }
});

// Admin Login
router.post('/admin/login', async (req, res) => {
  try {
    const { email, password } = req.body;
    const decryptedPassword = decryptPassword(password);
    
    const [rows] = await db.execute('SELECT * FROM users WHERE email = ? AND user_type = ?', [email, 'admin']);
    
    if (rows.length === 0) {
      return res.status(401).json({ message: 'Admin user not found' });
    }

    const user = rows[0];
    
    const isValidPassword = await bcrypt.compare(decryptedPassword, user.password_hash);
    
    if (!isValidPassword) {
      return res.status(401).json({ message: 'Invalid password' });
    }

    const token = jwt.sign(
      { id: user.id, email: user.email, role: user.user_type, school_id: user.school_id },
      process.env.JWT_SECRET,
      { expiresIn: '24h' }
    );

    res.json({
      token,
      user: {
        id: user.id,
        email: user.email,
        name: `${user.first_name} ${user.last_name}`,
        role: user.user_type,
        school_id: user.school_id
      }
    });
  } catch (error) {
    res.status(500).json({ message: 'Server error: ' + error.message });
  }
});

// School Login
router.post('/school/login', async (req, res) => {
  try {
    const { email, password } = req.body;
    const decryptedPassword = decryptPassword(password);
    
    const [rows] = await db.execute('SELECT * FROM users WHERE email = ? AND user_type = ?', [email, 'school']);
    if (rows.length === 0) {
      return res.status(401).json({ message: 'Invalid credentials' });
    }

    const user = rows[0];
    const isValidPassword = await bcrypt.compare(decryptedPassword, user.password_hash);
    
    if (!isValidPassword) {
      return res.status(401).json({ message: 'Invalid credentials' });
    }

    const token = jwt.sign(
      { id: user.id, email: user.email, role: user.user_type, school_id: user.school_id },
      process.env.JWT_SECRET,
      { expiresIn: '24h' }
    );

    res.json({
      token,
      user: {
        id: user.id,
        email: user.email,
        name: `${user.first_name} ${user.last_name}`,
        role: user.user_type,
        school_id: user.school_id
      }
    });
  } catch (error) {
    res.status(500).json({ message: 'Server error: ' + error.message });
  }
});

// Parent Login
router.post('/parent/login', async (req, res) => {
  try {
    const { email, password, fcm_token, device_id } = req.body;
    const decryptedPassword = decryptPassword(password);
    
    console.log('Parent login attempt:', email);
    
    const [rows] = await db.execute('SELECT * FROM users WHERE email = ? AND user_type = ?', [email, 'parent']);
    if (rows.length === 0) {
      console.log('Parent not found:', email);
      return res.status(401).json({ message: 'Invalid credentials' });
    }

    const user = rows[0];
    console.log('Parent found:', user.id, user.first_name, user.last_name);
    
    const isValidPassword = await bcrypt.compare(decryptedPassword, user.password_hash);
    
    if (!isValidPassword) {
      console.log('Invalid password for parent:', email);
      return res.status(401).json({ message: 'Invalid credentials' });
    }

    // Generate unlimited JWT (no expiresIn)
    const token = jwt.sign(
      { id: user.id, email: user.email, role: user.user_type, school_id: user.school_id },
      process.env.JWT_SECRET
    );
    
    // Delete old sessions for this user (one user one login)
    await db.execute('DELETE FROM user_sessions WHERE user_id = ?', [user.id]);
    
    // Insert new session
    await db.execute(
      'INSERT INTO user_sessions (user_id, device_id, fcm_token, jwt_token) VALUES (?, ?, ?, ?)',
      [user.id, device_id, fcm_token, token]
    );
    
    console.log('Parent login successful, session created for:', user.id);

    res.json({
      token,
      user: {
        id: user.id,
        email: user.email,
        name: `${user.first_name} ${user.last_name}`,
        role: user.user_type,
        school_id: user.school_id
      }
    });
  } catch (error) {
    console.error('Parent login error:', error);
    res.status(500).json({ message: 'Server error: ' + error.message });
  }
});

// Logout
router.post('/logout', async (req, res) => {
  try {
    const token = req.headers.authorization?.split(' ')[1];
    
    if (token) {
      // Delete session from database
      await db.execute('DELETE FROM user_sessions WHERE jwt_token = ?', [token]);
      
      // Update last_login in database
      try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        await db.execute(
          'UPDATE users SET last_login = NOW() WHERE id = ?', 
          [decoded.id]
        );
      } catch (jwtError) {
        // JWT might be invalid, but session already deleted
        console.log('JWT verification failed during logout:', jwtError.message);
      }
    }
    
    res.json({ message: 'Logged out successfully' });
  } catch (error) {
    res.status(500).json({ message: 'Server error: ' + error.message });
  }
});

module.exports = router;