import { Router } from "express";
import { z } from "zod";

import { prisma } from "../db";
import { requireAuth, type AuthRequest } from "../middleware/auth";

export const meRouter = Router();
meRouter.use(requireAuth);

meRouter.get("/", async (req: AuthRequest, res) => {
  const user = await prisma.user.findUnique({
    where: { id: req.userId! },
    select: {
      id: true,
      username: true,
      avatar: true,
      timezone: true,
      barkUrl: true,
      inappEnabled: true,
      barkEnabled: true,
    },
  });
  return res.json(user);
});

const settingsSchema = z.object({
  avatar: z.string().url().optional().nullable(),
  timezone: z.string().optional(),
  barkUrl: z.string().url().optional().nullable(),
  inappEnabled: z.boolean().optional(),
  barkEnabled: z.boolean().optional(),
});

meRouter.put("/settings", async (req: AuthRequest, res) => {
  const parsed = settingsSchema.safeParse(req.body);
  if (!parsed.success) {
    return res.status(400).json({ error: "Invalid payload" });
  }
  const user = await prisma.user.update({
    where: { id: req.userId! },
    data: parsed.data,
    select: {
      id: true,
      username: true,
      avatar: true,
      timezone: true,
      barkUrl: true,
      inappEnabled: true,
      barkEnabled: true,
    },
  });
  return res.json(user);
});
