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

const router = express.Router();

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 contacts = await storage.getInsuranceContactsByUser(userId);
    return res.json(contacts);
  } catch (err) {
    return res.status(500).json({ error: "Failed to fetch insurance contacts", details: String(err) });
  }
});

router.post("/", async (req: Request, res: Response): Promise<any> => {
  try {
    const userId = req.user?.id;
    if (!userId) return res.status(401).json({ message: "Unauthorized" });
    const { name, phoneNumber } = req.body;
    if (!name?.trim()) return res.status(400).json({ message: "Insurance company name is required" });
    const contact = await storage.createInsuranceContact({
      userId,
      name: name.trim(),
      phoneNumber: phoneNumber?.trim() || undefined,
    });
    return res.status(201).json(contact);
  } catch (err) {
    return res.status(500).json({ error: "Failed to create insurance contact", details: String(err) });
  }
});

router.put("/:id", async (req: Request, res: Response): Promise<any> => {
  try {
    const userId = req.user?.id;
    if (!userId) return res.status(401).json({ message: "Unauthorized" });
    const id = Number(req.params.id);
    if (isNaN(id)) return res.status(400).json({ message: "Invalid ID" });
    const { name, phoneNumber } = req.body;
    if (name !== undefined && !name?.trim()) return res.status(400).json({ message: "Name cannot be empty" });
    const contact = await storage.updateInsuranceContact(id, {
      name: name?.trim(),
      phoneNumber: phoneNumber?.trim() || undefined,
    });
    return res.json(contact);
  } catch (err) {
    return res.status(500).json({ error: "Failed to update insurance contact", details: String(err) });
  }
});

router.delete("/:id", async (req: Request, res: Response): Promise<any> => {
  try {
    const userId = req.user?.id;
    if (!userId) return res.status(401).json({ message: "Unauthorized" });
    const id = Number(req.params.id);
    if (isNaN(id)) return res.status(400).json({ message: "Invalid ID" });
    const ok = await storage.deleteInsuranceContact(userId, id);
    if (!ok) return res.status(404).json({ message: "Insurance contact not found" });
    return res.status(204).send();
  } catch (err) {
    return res.status(500).json({ error: "Failed to delete insurance contact", details: String(err) });
  }
});

export default router;
