import { Router, Request, Response } from "express";
import { prisma as db } from "@repo/db/client";

const router = Router();

// GET /api/selenium-settings
router.get("/", async (req: Request, res: Response): Promise<any> => {
  try {
    const userId = req.user?.id;
    if (!userId) return res.status(401).json({ message: "Unauthorized" });

    const settings = await db.seleniumSettings.findUnique({ where: { userId } });
    return res.status(200).json({ paymentGroupId: settings?.paymentGroupId ?? "" });
  } catch (err) {
    return res.status(500).json({ error: "Failed to fetch Selenium settings", details: String(err) });
  }
});

// PUT /api/selenium-settings
router.put("/", async (req: Request, res: Response): Promise<any> => {
  try {
    const userId = req.user?.id;
    if (!userId) return res.status(401).json({ message: "Unauthorized" });

    const { paymentGroupId } = req.body;
    if (typeof paymentGroupId !== "string") {
      return res.status(400).json({ message: "paymentGroupId must be a string" });
    }

    const settings = await db.seleniumSettings.upsert({
      where: { userId },
      update: { paymentGroupId: paymentGroupId.trim() },
      create: { userId, paymentGroupId: paymentGroupId.trim() },
    });

    return res.status(200).json({ paymentGroupId: settings.paymentGroupId });
  } catch (err) {
    return res.status(500).json({ error: "Failed to save Selenium settings", details: String(err) });
  }
});

export default router;
