import { Router } from "express";

import { authenticate } from "../../middleware/auth.js";
import { validate } from "../../middleware/validate.js";
import { asyncHandler } from "../../utils/http.js";
import { loginSchema, preferencesPatchSchema } from "./auth.schemas.js";
import { getAuthUserById, getUserPreferences, login, updateUserPreferences } from "./auth.service.js";

export const authRouter = Router();

authRouter.post(
  "/login",
  validate({ body: loginSchema }),
  asyncHandler(async (request, response) => {
    const session = await login(request.body.email, request.body.password);
    response.json(session);
  })
);

authRouter.get(
  "/me",
  authenticate,
  asyncHandler(async (request, response) => {
    const user = await getAuthUserById(request.authUser!.id);
    response.json({ user });
  })
);

authRouter.get(
  "/preferences",
  authenticate,
  asyncHandler(async (request, response) => {
    response.json({ data: await getUserPreferences(request.authUser!.id) });
  })
);

authRouter.patch(
  "/preferences",
  authenticate,
  validate({ body: preferencesPatchSchema }),
  asyncHandler(async (request, response) => {
    response.json({ data: await updateUserPreferences(request.authUser!.id, request.body) });
  })
);
