const express = require('express');
const router = express.Router();

const { getSetting } = require('../db/database');
const { login, cookieOpts, COOKIE_NAME } = require('../services/authService');
const { standardizeError } = require('../middleware/errorFormatter');

// POST /api/auth/login
// Public endpoint - no CSRF protection needed (no session to hijack)
router.post('/login', async (req, res) => {
  // Respect admin-configured login method toggle
  if (getSetting('local_login_enabled') === 'false') {
    return res.status(403).json(standardizeError('Local username/password login is not enabled on this server.', 'FORBIDDEN'));
  }

  const { username, password } = req.body;
  if (!username || !password) {
    return res.status(400).json(standardizeError('Username and password are required', 'VALIDATION_ERROR', !username ? 'username' : 'password'));
  }

  try {
    const result = await login(username, password);
    if (!result) {
      return res.status(401).json(standardizeError('Invalid username or password', 'AUTH_ERROR'));
    }

    res.cookie(COOKIE_NAME, result.sessionId, cookieOpts(req));
    res.json({ user: result.user });
  } catch (err) {
    console.error('Login error:', err);
    res.status(500).json(standardizeError('Login failed', 'SERVER_ERROR'));
  }
});

module.exports = router;
