import { Request, Response } from 'express';
import * as authService from '../services/auth.service.js';

export async function register(req: Request, res: Response) {
  const parsed = authService.registerSchema.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: parsed.error.flatten() });
    return;
  }

  try {
    const user = await authService.register(parsed.data);
    res.status(201).json(user);
  } catch (err: any) {
    res.status(409).json({ error: err.message });
  }
}

export async function login(req: Request, res: Response) {
  const parsed = authService.loginSchema.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: parsed.error.flatten() });
    return;
  }

  try {
    const tokens = await authService.login(parsed.data);
    res.json(tokens);
  } catch (err: any) {
    res.status(401).json({ error: err.message });
  }
}

export async function logout(req: Request, res: Response) {
  const { refreshToken } = req.body;
  if (!refreshToken) {
    res.status(400).json({ error: 'refreshToken is required' });
    return;
  }

  await authService.logout(refreshToken);
  res.status(204).send();
}