import { Router } from "express";
import type { Request } from "express";
import { graphqlClient } from "../lib/graphqlClient";
import { respondWithError } from "../lib/error";
import {
  GetWorkDocument,
  WorksDocument,
  CreateWorkDocument,
} from "../../shared/generated/graphql";

const router = Router();

// GET /api/works
interface GqlRequest extends Request {
  gql?: typeof graphqlClient;
}

router.get("/", async (req: GqlRequest, res) => {
  try {
    const variables = {
      limit: req.query.limit ? Number(req.query.limit) : undefined,
      offset: req.query.offset ? Number(req.query.offset) : undefined,
      language: req.query.language as string | undefined,
      authorId: req.query.authorId as string | undefined,
      tagId: req.query.tagId as string | undefined,
      search: req.query.search as string | undefined,
    };
    const client = req.gql || graphqlClient;
    const { works } = await client.request(WorksDocument, variables);
    res.json(works);
  } catch (error) {
    respondWithError(res, error, "Failed to fetch works");
  }
});

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

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

export default router;
