'use strict';
const jwt = require('jsonwebtoken');
const { db } = require('../db');

const JWT_SECRET = process.env.JWT_SECRET || 'tous-cino-super-secret-change-me';

function sign(user) {
  return jwt.sign({ id: user.id, email: user.email, is_admin: user.is_admin ? 1 : 0 }, JWT_SECRET, {
    expiresIn: '30d',
  });
}

function userFromToken(token) {
  try {
    const payload = jwt.verify(token, JWT_SECRET);
    return db.prepare('SELECT id, name, email, phone, is_admin, created_at FROM users WHERE id = ?').get(payload.id);
  } catch {
    return null;
  }
}

function attachUser(req, res, next) {
  req.user = null;
  const token = req.cookies && req.cookies.tc_token;
  if (token) req.user = userFromToken(token);
  res.locals.user = req.user;
  next();
}

function requireAuth(req, res, next) {
  if (!req.user) {
    if (req.path.startsWith('/api/')) {
      return res.status(401).json({ error: 'You must be signed in.' });
    }
    return res.redirect('/account/login?next=' + encodeURIComponent(req.originalUrl));
  }
  next();
}

function requireAdmin(req, res, next) {
  if (!req.user || !req.user.is_admin) {
    if (req.path.startsWith('/api/')) {
      return res.status(403).json({ error: 'Admins only.' });
    }
    return res.status(403).send('Access denied — admins only.');
  }
  next();
}

module.exports = { JWT_SECRET, sign, attachUser, requireAuth, requireAdmin };
