const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
require('dotenv').config();

// === Conexión a MongoDB ===
mongoose.connect(process.env.MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => console.log('[auth.js] Conectado a MongoDB'))
  .catch(err => console.error(' [auth.js] Error de conexión:', err));

// === Modelo de usuario ===
const userSchema = new mongoose.Schema({
  name: String,
  username: { type: String, unique: true, required: true },
  email: { type: String, unique: true, required: true },
  passwordHash: String,
  role: { type: String, enum: ['coach', 'athlete'], required: true },
  language: { type: String, default: 'es' }, // <- CAMPO AÑADIDO
  createdAt: { type: Date, default: Date.now }
});

const User = mongoose.model('User', userSchema);

// === Ruta: Registro de usuario ===
router.post('/register', async (req, res) => {
  const { name, username, email, password, role, language } = req.body;

  try {
    const existing = await User.findOne({ email });
    if (existing) return res.status(400).send('Correo ya registrado');

    const passwordHash = await bcrypt.hash(password, 10);
    const user = new User({ name, username, email, passwordHash, role, language });
    await user.save();

    res.redirect('/index.html');
  } catch (error) {
    console.error('Error en registro:', error);
    res.status(500).send('Error interno del servidor');
  }
});

// === Ruta: Login de usuario ===
router.post('/login', async (req, res) => {
  const { email, password } = req.body;

  try {
    const user = await User.findOne({ email });
    if (!user) return res.status(401).send('Correo no registrado');

    const valid = await bcrypt.compare(password, user.passwordHash);
    if (!valid) return res.status(401).send('Contraseña incorrecta');

    res.json({
      userId: user._id,
      name: user.name,
      role: user.role,
      language: user.language // <- También puedes enviar este dato al frontend
    });
  } catch (error) {
    console.error('Error en login:', error);
    res.status(500).send('Error interno del servidor');
  }
});

module.exports = router;
