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

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));

// Schema corregido
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' },
  createdAt: { type: Date, default: Date.now },
  idPersonalizado: { type: String, unique: true } // <- CAMBIO AQUÍ
});

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

// Genera ID como JP, FM, etc.
function generarIdPersonalizado(name) {
  const [nombre, apellido = ''] = name.trim().toUpperCase().split(' ');
  return (nombre[0] || '') + (apellido[0] || '');
}

// 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);

    let idPersonalizado = generarIdPersonalizado(name);

    const repetido = await User.findOne({ idPersonalizado });
    if (repetido) {
      idPersonalizado += Math.floor(100 + Math.random() * 900);
    }

    const user = new User({
      name,
      username,
      email,
      passwordHash,
      role,
      language,
      idPersonalizado // <- CAMBIO AQUÍ
    });

    await user.save();

    res.status(200).send('Usuario registrado correctamente');
  } catch (error) {
    console.error('Error en registro:', error);
    res.status(500).send('Error interno del servidor');
  }
});

// Login
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
    });
  } catch (error) {
    console.error('Error en login:', error);
    res.status(500).send('Error interno del servidor');
  }
});

module.exports = router;
