import { Response } from 'express';
import { AuthRequest } from '../middlewares/auth.middleware.js';
import * as usersService from '../services/users.service.js';

export async function get(req: AuthRequest, res: Response): Promise<void> {
  try {
    const user = await usersService.getUser(req.userId!);
    res.json(user);
  } catch (err: any) {
    res.status(404).json({ error: err.message });
  }
}

export async function getProfile(req: AuthRequest, res: Response): Promise<void> {
  try {
    const profile = await usersService.getProfile(req.userId!);
    res.json(profile);
  } catch (err: any) {
    res.status(404).json({ error: err.message });
  }
}

export async function update(req: AuthRequest, res: Response): Promise<void> {
  const parsed = usersService.updateUserSchema.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: parsed.error.flatten() });
    return;
  }

  try {
    const user = await usersService.updateUser(req.userId!, parsed.data);
    res.json(user);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
}

export async function updateProfile(req: AuthRequest, res: Response): Promise<void> {
  const parsed = usersService.updateProfileSchema.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: parsed.error.flatten() });
    return;
  }

  try {
    const profile = await usersService.updateProfile(req.userId!, parsed.data);
    res.json(profile);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
}

export async function remove(req: AuthRequest, res: Response): Promise<void> {
  try {
    await usersService.deleteUser(req.userId!);
    res.status(204).send();
  } catch (err: any) {
    res.status(404).json({ error: err.message });
  }
}