const express = require('express');
const { v4: uuidv4 } = require('uuid');
const { getPool } = require('../config/database');
const { authenticateToken } = require('../middleware/auth');
const { updateProfileValidation, handleValidationErrors } = require('../utils/validation');

const router = express.Router();

// Get user profile
router.get('/profile', authenticateToken, async (req, res) => {
  try {
    const pool = getPool();
    
    const [users] = await pool.execute(
      'SELECT id, username, email, avatar_url, is_verified, created_at, last_login_at FROM users WHERE id = ?',
      [req.user.id]
    );

    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        error: 'User not found'
      });
    }

    res.json({
      success: true,
      user: {
        id: users[0].id,
        username: users[0].username,
        email: users[0].email,
        avatarUrl: users[0].avatar_url,
        isVerified: users[0].is_verified,
        createdAt: users[0].created_at,
        lastLoginAt: users[0].last_login_at
      }
    });

  } catch (error) {
    console.error('Get profile error:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to get profile'
    });
  }
});

// Update user profile
router.put('/update-profile', authenticateToken, updateProfileValidation, handleValidationErrors, async (req, res) => {
  try {
    const { username, email } = req.body;
    const pool = getPool();

    // Check if username or email already exists
    if (username || email) {
      const [existingUsers] = await pool.execute(
        'SELECT id FROM users WHERE (email = ? OR username = ?) AND id != ?',
        [email || req.user.email, username || req.user.username, req.user.id]
      );

      if (existingUsers.length > 0) {
        return res.status(400).json({
          success: false,
          error: 'Username or email already exists'
        });
      }
    }

    // Build update query
    const updates = [];
    const values = [];

    if (username) {
      updates.push('username = ?');
      values.push(username);
    }

    if (email) {
      updates.push('email = ?');
      values.push(email);
    }

    if (updates.length === 0) {
      return res.status(400).json({
        success: false,
        error: 'No fields to update'
      });
    }

    values.push(req.user.id);

    await pool.execute(
      `UPDATE users SET ${updates.join(', ')} WHERE id = ?`,
      values
    );

    // Get updated user data
    const [users] = await pool.execute(
      'SELECT id, username, email, avatar_url, is_verified, created_at, last_login_at FROM users WHERE id = ?',
      [req.user.id]
    );

    res.json({
      success: true,
      message: 'Profile updated successfully',
      user: {
        id: users[0].id,
        username: users[0].username,
        email: users[0].email,
        avatarUrl: users[0].avatar_url,
        isVerified: users[0].is_verified,
        createdAt: users[0].created_at,
        lastLoginAt: users[0].last_login_at
      }
    });

  } catch (error) {
    console.error('Update profile error:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to update profile'
    });
  }
});

// Delete account
router.delete('/delete-account', authenticateToken, async (req, res) => {
  try {
    const pool = getPool();

    // Delete user sessions
    await pool.execute(
      'DELETE FROM user_sessions WHERE user_id = ?',
      [req.user.id]
    );

    // Delete user activity
    await pool.execute(
      'DELETE FROM user_activity WHERE user_id = ?',
      [req.user.id]
    );

    // Delete user
    await pool.execute(
      'DELETE FROM users WHERE id = ?',
      [req.user.id]
    );

    res.json({
      success: true,
      message: 'Account deleted successfully'
    });

  } catch (error) {
    console.error('Delete account error:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to delete account'
    });
  }
});

// Get user activity
router.get('/activity', authenticateToken, async (req, res) => {
  try {
    const pool = getPool();
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;

    const [activities] = await pool.execute(
      `SELECT id, activity_type, ip_address, user_agent, created_at 
       FROM user_activity 
       WHERE user_id = ? 
       ORDER BY created_at DESC 
       LIMIT ? OFFSET ?`,
      [req.user.id, limit, offset]
    );

    const [total] = await pool.execute(
      'SELECT COUNT(*) as count FROM user_activity WHERE user_id = ?',
      [req.user.id]
    );

    res.json({
      success: true,
      activities: activities.map(activity => ({
        id: activity.id,
        type: activity.activity_type,
        ipAddress: activity.ip_address,
        userAgent: activity.user_agent,
        createdAt: activity.created_at
      })),
      pagination: {
        page,
        limit,
        total: total[0].count,
        totalPages: Math.ceil(total[0].count / limit)
      }
    });

  } catch (error) {
    console.error('Get activity error:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to get activity'
    });
  }
});

module.exports = router; 