import express from 'express';
import api from '../config/api.js';

const router = express.Router();

const COOKIE_OPTS = { httpOnly: true, sameSite: 'lax', maxAge: 30 * 24 * 60 * 60 * 1000 };

router.get('/login', (req, res) => {
  if (res.locals.customer) return res.redirect('/');
  res.render('pages/login', { title: 'Login', error: null });
});

router.post('/login', async (req, res) => {
  const { email, password } = req.body;
  try {
    const { data } = await api.post('/customer-auth/login', { email, password });
    res.cookie('rmt_token', data.token, COOKIE_OPTS);
    res.cookie('rmt_customer', JSON.stringify(data.customer), COOKIE_OPTS);
    res.redirect('/');
  } catch (err) {
    console.error('Login error:', err.message);
    res.render('pages/login', { title: 'Login', error: err.response?.data?.message || 'Login failed.' });
  }
});

router.get('/register', (req, res) => {
  if (res.locals.customer) return res.redirect('/');
  res.render('pages/register', { title: 'Register', error: null });
});

router.post('/register', async (req, res) => {
  const { name, email, phone, password } = req.body;
  try {
    const { data } = await api.post('/customer-auth/register', { name, email, phone, password });
    res.cookie('rmt_token', data.token, COOKIE_OPTS);
    res.cookie('rmt_customer', JSON.stringify(data.customer), COOKIE_OPTS);
    res.redirect('/');
  } catch (err) {
    console.error('Register error:', err.message);
    res.render('pages/register', { title: 'Register', error: err.response?.data?.message || 'Registration failed.' });
  }
});

router.get('/logout', (req, res) => {
  res.clearCookie('rmt_token');
  res.clearCookie('rmt_customer');
  res.redirect('/');
});

export default router;
