// src/routes/userRoutes.js
const express = require('express');
const db = require('../db');
const auth = require('../middleware/authMiddleware');

const router = express.Router();

// GET /users/me
router.get('/me', auth, async (req, res) => {
  try {
    // Get user basic information
    const { rows } = await db.query(
      `SELECT id, phone_number, name, role, user_type, created_at, last_login_at, avatar_url, language, timezone
       FROM users
       WHERE id = $1`,
      [req.user.id]
    );

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

    const user = rows[0];

    // Get active devices count
    const deviceCountResult = await db.query(
      `SELECT COUNT(*) as count FROM user_devices WHERE user_id = $1 AND is_active = true`,
      [req.user.id]
    );
    const activeDevicesCount = parseInt(deviceCountResult.rows[0].count, 10);

    // Get user's saved locations (addresses)
    const locationsResult = await db.query(
      `SELECT 
        id,
        country,
        state,
        district,
        city_village,
        pincode,
        lat,
        lng,
        location_type,
        is_saved_address,
        source_type,
        source_confidence,
        created_at,
        updated_at
       FROM locations
       WHERE user_id = $1 AND is_saved_address = true
       ORDER BY updated_at DESC`,
      [req.user.id]
    );

    const locations = locationsResult.rows.map(loc => ({
      id: loc.id,
      country: loc.country,
      state: loc.state,
      district: loc.district,
      city_village: loc.city_village,
      pincode: loc.pincode,
      coordinates: loc.lat && loc.lng ? {
        latitude: parseFloat(loc.lat),
        longitude: parseFloat(loc.lng)
      } : null,
      location_type: loc.location_type,
      is_saved_address: loc.is_saved_address,
      source_type: loc.source_type,
      source_confidence: loc.source_confidence,
      created_at: loc.created_at,
      updated_at: loc.updated_at
    }));

    // Get primary location (most recent saved address, or first if none)
    const primaryLocation = locations.length > 0 ? locations[0] : null;

    return res.json({
      id: user.id,
      phone_number: user.phone_number,
      name: user.name,
      role: user.role,
      user_type: user.user_type,
      avatar_url: user.avatar_url,
      language: user.language,
      timezone: user.timezone,
      created_at: user.created_at,
      last_login_at: user.last_login_at,
      active_devices_count: activeDevicesCount,
      location: primaryLocation, // Primary/saved location for convenience
      locations: locations // All saved locations
    });
  } catch (err) {
    console.error('get me error', err);
    return res.status(500).json({ error: 'Internal server error' });
  }
});

// PUT /users/me
router.put('/me', auth, async (req, res) => {
  try {
    const { name, user_type } = req.body;

    if (!name || !user_type) {
      return res.status(400).json({ error: 'name and user_type are required' });
    }

    const { rows } = await db.query(
      `
      UPDATE users
      SET name = $1,
          user_type = $2
      WHERE id = $3
      RETURNING id, phone_number, name, role, user_type
      `,
      [name, user_type, req.user.id]
    );

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

    return res.json(rows[0]);
  } catch (err) {
    console.error('update me error', err);
    return res.status(500).json({ error: 'Internal server error' });
  }
});

// GET /users/me/devices - List all active devices
router.get('/me/devices', auth, async (req, res) => {
  try {
    const { rows } = await db.query(
      `
      SELECT 
        device_identifier,
        device_platform,
        device_model,
        os_version,
        app_version,
        language_code,
        timezone,
        first_seen_at,
        last_seen_at,
        is_active
      FROM user_devices
      WHERE user_id = $1 AND is_active = true
      ORDER BY last_seen_at DESC
      `,
      [req.user.id]
    );

    return res.json({ devices: rows });
  } catch (err) {
    console.error('get devices error', err);
    return res.status(500).json({ error: 'Internal server error' });
  }
});

// DELETE /users/me/devices/:device_id - Revoke/logout a specific device
router.delete('/me/devices/:device_id', auth, async (req, res) => {
  try {
    const { device_id } = req.params;

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

    // Mark device as inactive
    await db.query(
      `UPDATE user_devices SET is_active = false WHERE user_id = $1 AND device_identifier = $2`,
      [req.user.id, device_id]
    );

    // Revoke all refresh tokens for this device
    const { revokeRefreshToken } = require('../services/tokenService');
    await revokeRefreshToken(req.user.id, device_id);

    // Log the action
    try {
      await db.query(
        `INSERT INTO auth_audit (user_id, action, status, device_id, ip_address, user_agent, meta)
         VALUES ($1, 'device_revoked', 'success', $2, $3, $4, $5)`,
        [
          req.user.id,
          device_id,
          req.ip,
          req.headers['user-agent'],
          JSON.stringify({ revoked_by: 'user' }),
        ]
      );
    } catch (auditErr) {
      console.error('Failed to log device revocation', auditErr);
    }

    return res.json({ ok: true, message: 'Device logged out successfully' });
  } catch (err) {
    console.error('revoke device error', err);
    return res.status(500).json({ error: 'Internal server error' });
  }
});

// POST /users/me/devices/:device_id/logout-all - Logout all other devices (keep current)
router.post('/me/logout-all-other-devices', auth, async (req, res) => {
  try {
    // Get current device_id from refresh token if available, or from request
    // For now, we'll need device_id in request body or header
    const currentDeviceId = req.headers['x-device-id'] || req.body.current_device_id;

    if (!currentDeviceId) {
      return res.status(400).json({ error: 'current_device_id is required in header or body' });
    }

    // Mark all other devices as inactive
    const result = await db.query(
      `UPDATE user_devices 
       SET is_active = false 
       WHERE user_id = $1 AND device_identifier != $2 AND is_active = true
       RETURNING device_identifier`,
      [req.user.id, currentDeviceId]
    );

    const revokedDevices = result.rows.map((row) => row.device_identifier);

    // Revoke refresh tokens for all other devices
    const { revokeRefreshToken } = require('../services/tokenService');
    for (const deviceId of revokedDevices) {
      await revokeRefreshToken(req.user.id, deviceId);
    }

    // Log the action
    try {
      await db.query(
        `INSERT INTO auth_audit (user_id, action, status, device_id, ip_address, user_agent, meta)
         VALUES ($1, 'logout_all_other_devices', 'success', $2, $3, $4, $5)`,
        [
          req.user.id,
          currentDeviceId,
          req.ip,
          req.headers['user-agent'],
          JSON.stringify({
            revoked_devices_count: revokedDevices.length,
            revoked_devices: revokedDevices,
          }),
        ]
      );
    } catch (auditErr) {
      console.error('Failed to log logout all action', auditErr);
    }

    return res.json({
      ok: true,
      message: `Logged out ${revokedDevices.length} device(s)`,
      revoked_devices_count: revokedDevices.length,
    });
  } catch (err) {
    console.error('logout all other devices error', err);
    return res.status(500).json({ error: 'Internal server error' });
  }
});

module.exports = router;
