import express, { Request, Response } from "express";
import { storage } from "../storage";

const router = express.Router();

// GET /api/procedure-timeslot
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 record = await storage.getProcedureTimeslot(userId);
    return res.status(200).json(record ?? null);
  } catch (err) {
    return res.status(500).json({ error: "Failed to fetch procedure timeslot", details: String(err) });
  }
});

// PUT /api/procedure-timeslot
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 { data } = req.body;
    if (!data || typeof data !== "object") {
      return res.status(400).json({ error: "Invalid data payload" });
    }

    const record = await storage.upsertProcedureTimeslot(userId, data);
    return res.status(200).json(record);
  } catch (err) {
    return res.status(500).json({ error: "Failed to save procedure timeslot", details: String(err) });
  }
});

export default router;
