import { Router } from "express";
import type { Request } from "express";
import { graphqlClient } from "../lib/graphqlClient";
import { respondWithError } from "../lib/error";
import {
  GetCommentDocument,
  CommentsDocument,
  CreateCommentDocument,
  UpdateCommentDocument,
  DeleteCommentDocument,
  type GetCommentQuery,
  type CommentsQuery,
  type CreateCommentMutation,
  type UpdateCommentMutation,
  type DeleteCommentMutation,
} from "../../shared/generated/graphql";

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

const router = Router();

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

// GET /api/comments
router.get("/", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const { comments } = await client.request<CommentsQuery>(CommentsDocument, {
      workId: req.query.workId as string | undefined,
      translationId: req.query.translationId as string | undefined,
      userId: req.query.userId as string | undefined,
      limit: req.query.limit ? Number(req.query.limit) : undefined,
      offset: req.query.offset ? Number(req.query.offset) : undefined,
    });
    res.json(comments);
  } catch (error) {
    respondWithError(res, error, "Failed to fetch comments");
  }
});

// POST /api/comments
router.post("/", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const { createComment } = await client.request<CreateCommentMutation>(
      CreateCommentDocument,
      { input: req.body }
    );
    res.status(201).json(createComment);
  } catch (error) {
    respondWithError(res, error, "Failed to create comment");
  }
});

// PUT /api/comments/:id
router.put("/:id", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const { updateComment } = await client.request<UpdateCommentMutation>(
      UpdateCommentDocument,
      { id: req.params.id, input: req.body }
    );
    res.json(updateComment);
  } catch (error) {
    respondWithError(res, error, "Failed to update comment");
  }
});

// DELETE /api/comments/:id
router.delete("/:id", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const { deleteComment } = await client.request<DeleteCommentMutation>(
      DeleteCommentDocument,
      { id: req.params.id }
    );
    res.json({ success: deleteComment });
  } catch (error) {
    respondWithError(res, error, "Failed to delete comment");
  }
});

export default router;
