const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const db = require('../db');

const SECRET = process.env.JWT_SECRET || 'pulse-mv-secret-key-2024';

// POST /api/auth/login
router.post('/login', async (req, res) => {
  const { username, password } = req.body;
  
  try {
    const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
    if (!user) {
      return res.status(401).json({ error: 'ޔޫޒަރނޭމް ނުވަތަ ޕާސްވޯޑް ނުބައި' });
    }

    const validPassword = await bcrypt.compare(password, user.password);
    if (!validPassword) {
      return res.status(401).json({ error: 'ޔޫޒަރނޭމް ނުވަތަ ޕާސްވޯޑް ނުބައި' });
    }

    const token = jwt.sign({
      id: user.id,
      username: user.username,
      full_name: user.full_name || user.username,
      avatar_url: user.avatar_url || null,
      role: user.role
    }, SECRET, { expiresIn: '24h' });
    res.json({
      token,
      user: {
        id: user.id,
        username: user.username,
        full_name: user.full_name || user.username,
        avatar_url: user.avatar_url || null,
        role: user.role
      }
    });
  } catch (err) {
    res.status(500).json({ error: 'ސާވަރަށް މައްސަލައެއް ދިމާވެއްޖެ' });
  }
});

// GET /api/auth/me
router.get('/me', (req, res) => {
  const authHeader = req.headers.authorization;
  if (!authHeader) return res.status(401).json({ error: 'ލޮގިންއެއް ނުވޭ' });

  const token = authHeader.split(' ')[1];
  try {
    const decoded = jwt.verify(token, SECRET);
    res.json({ user: decoded });
  } catch (err) {
    res.status(401).json({ error: 'ސެޝަން މުއްދަތު ހަމަވެއްޖެ' });
  }
});

module.exports = router;
