import { Router } from "express";
import type { Request } from "express";
import { graphqlClient } from "../lib/graphqlClient";
import { respondWithError } from "../lib/error";
import {
  GetLikeDocument,
  LikesDocument,
  CreateLikeDocument,
  DeleteLikeDocument,
} from "../../shared/generated/graphql";

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

const router = Router();

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

// GET /api/likes
router.get("/", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const { likes } = await client.request(LikesDocument, {
      workId: req.query.workId as string | undefined,
      translationId: req.query.translationId as string | undefined,
      commentId: req.query.commentId as string | undefined,
    });
    res.json(likes);
  } catch (error) {
    respondWithError(res, error, "Failed to fetch likes");
  }
});

// POST /api/likes
router.post("/", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const { createLike } = await client.request(CreateLikeDocument, {
      input: req.body,
    });
    res.status(201).json(createLike);
  } catch (error) {
    respondWithError(res, error, "Failed to create like");
  }
});

// DELETE /api/likes/:id
router.delete("/:id", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const { deleteLike } = await client.request(DeleteLikeDocument, {
      id: req.params.id,
    });
    res.json({ success: deleteLike });
  } catch (error) {
    respondWithError(res, error, "Failed to delete like");
  }
});

export default router;
