const { Router } = require('express');
const { pool } = require('../db/pool');
const { login, logout } = require('../auth/auth.service');
const { requireAuth } = require('../middlewares/auth.middleware');

const router = Router();

router.post('/login', async (req, res, next) => {
  try {
    const result = await login(
      pool,
      {
        identifier: req.body?.identifier,
        password: req.body?.password
      },
      {
        userAgent: req.headers['user-agent'] || '',
        ipAddress: req.ip || ''
      }
    );

    res.json({ ok: true, data: result });
  } catch (error) {
    next(error);
  }
});

router.get('/me', requireAuth, (req, res) => {
  res.json({ ok: true, data: req.user });
});

router.post('/logout', requireAuth, async (req, res, next) => {
  try {
    await logout(pool, req.authToken);
    res.json({ ok: true });
  } catch (error) {
    next(error);
  }
});

module.exports = router;
