const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { User, Project, Education, JobExperience, Resume, Social } = require('./models');

const router = express.Router();

const JWT_SECRET = process.env.JWT_SECRET;

// Register route
router.post('/register', async (req, res) => {
  const { username, password } = req.body;
  const user = new User({ username, password });
  await user.save();
  res.send({ message: 'User registered successfully' });
});

// Login route
router.post('/login', async (req, res) => {
  const { username, password } = req.body;
  const user = await User.findOne({ username });
  if (!user || !(await user.comparePassword(password))) {
    return res.status(401).send({ error: 'Invalid username or password' });
  }
  const token = jwt.sign({ userId: user._id }, JWT_SECRET, { expiresIn: '1h' });
  res.send({ token });
});

// Middleware to authenticate and authorize
const authenticate = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) {
    return res.status(401).send({ error: 'Unauthorized' });
  }
  try {
    const payload = jwt.verify(token, JWT_SECRET);
    req.user = payload;
    next();
  } catch (err) {
    return res.status(401).send({ error: 'Unauthorized' });
  }
};

// Protect admin routes
router.use('/admin', authenticate);

// Admin routes
router.post('/admin/projects', async (req, res) => {
  const project = new Project(req.body);
  await project.save();
  res.send(project);
});

router.post('/admin/education', async (req, res) => {
  const education = new Education(req.body);
  await education.save();
  res.send(education);
});

router.post('/admin/job-experience', async (req, res) => {
  const jobExperience = new JobExperience(req.body);
  await jobExperience.save();
  res.send(jobExperience);
});

router.post('/admin/resume', async (req, res) => {
  const resume = new Resume(req.body);
  await resume.save();
  res.send(resume);
});

router.post('/admin/socials', async (req, res) => {
  const social = new Social(req.body);
  await social.save();
  res.send(social);
});

module.exports = router;
