import { Router } from "express";
import type { Request } from "express";
import { graphqlClient } from "../lib/graphqlClient";
import { respondWithError } from "../lib/error";
import {
  GetBookmarkDocument,
  BookmarksDocument,
  CreateBookmarkDocument,
  DeleteBookmarkDocument,
} from "../../shared/generated/graphql";

interface GqlRequest extends Request {
  gql?: typeof graphqlClient;
}

const router = Router();

// GET /api/bookmarks/:id
router.get("/:id", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const { bookmark } = await client.request(GetBookmarkDocument, {
      id: req.params.id,
    });
    if (!bookmark)
      return res.status(404).json({ message: "Bookmark not found" });
    res.json(bookmark);
  } catch (error) {
    respondWithError(res, error, "Failed to fetch bookmark");
  }
});

// GET /api/bookmarks
router.get("/", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const data = (await client.request(BookmarksDocument, {
      userId: req.query.userId as string | undefined,
      workId: req.query.workId as string | undefined,
      limit: req.query.limit ? Number(req.query.limit) : undefined,
      offset: req.query.offset ? Number(req.query.offset) : undefined,
    })) as import("../../shared/generated/graphql").BookmarksQuery;
    res.json(data.bookmarks);
  } catch (error) {
    respondWithError(res, error, "Failed to fetch bookmarks");
  }
});

// POST /api/bookmarks
router.post("/", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const data = (await client.request(CreateBookmarkDocument, {
      input: req.body,
    })) as import("../../shared/generated/graphql").CreateBookmarkMutation;
    res.status(201).json(data.createBookmark);
  } catch (error) {
    respondWithError(res, error, "Failed to create bookmark");
  }
});

// DELETE /api/bookmarks/:id
router.delete("/:id", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const data = (await client.request(DeleteBookmarkDocument, {
      id: req.params.id,
    })) as import("../../shared/generated/graphql").DeleteBookmarkMutation;
    res.json({ success: data.deleteBookmark });
  } catch (error) {
    respondWithError(res, error, "Failed to delete bookmark");
  }
});

export default router;
