const router = require('express').Router();
const { getSupabaseClient } = require('./supabaseClient');

// POST /sign-in
router.post('/sign-in', async (req, res) => {
  const { email, password } = req.body;
  const supabase = getSupabaseClient();
  const { data, error } = await supabase.auth.signInWithPassword({ email, password });
  if (error) return res.status(400).json({ error: error.message });
  res.json(data);
});

// POST /sign-up
router.post('/sign-up', async (req, res) => {
  const { email, password } = req.body;
  const supabase = getSupabaseClient();
  const { data, error } = await supabase.auth.signUp({ email, password });
  if (error) return res.status(400).json({ error: error.message });
  res.json(data);
});

// POST /sign-out
router.post('/sign-out', async (req, res) => {
  const { access_token } = req.body;
  const supabase = getSupabaseClient();
  supabase.auth.setSession({ access_token, refresh_token: '' });
  const { error } = await supabase.auth.signOut();
  if (error) return res.status(400).json({ error: error.message });
  res.json({ success: true });
});

// POST /reset-password
router.post('/reset-password', async (req, res) => {
  const { email } = req.body;
  const supabase = getSupabaseClient();
  const { data, error } = await supabase.auth.resetPasswordForEmail(email);
  if (error) return res.status(400).json({ error: error.message });
  res.json(data);
});

// POST /update-password
router.post('/update-password', async (req, res) => {
  const { access_token, newPassword } = req.body;
  const supabase = getSupabaseClient();
  supabase.auth.setSession({ access_token, refresh_token: '' });
  const { data, error } = await supabase.auth.updateUser({ password: newPassword });
  if (error) return res.status(400).json({ error: error.message });
  res.json(data);
});

module.exports = router; 