import { Router } from "express";
import type { Request } from "express";
import { graphqlClient } from "../lib/graphqlClient";
import { respondWithError } from "../lib/error";
import {
  WorkStatsDocument,
  UserStatsDocument,
  BlogStatsDocument,
  CommentStatsDocument,
} from "../../shared/generated/graphql";

const router = Router();

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

router.get("/work", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const data = (await client.request(
      WorkStatsDocument,
      {}
    )) as import("../../shared/generated/graphql").WorkStatsQuery;
    res.json(data.works);
  } catch (error) {
    respondWithError(res, error, "Failed to fetch work stats");
  }
});

// GET /api/stats/user
router.get("/user", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const data = (await client.request(
      UserStatsDocument,
      {}
    )) as import("../../shared/generated/graphql").UserStatsQuery;
    res.json(data.users);
  } catch (error) {
    respondWithError(res, error, "Failed to fetch user stats");
  }
});

// GET /api/stats/blog
router.get("/blog", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const data = (await client.request(
      BlogStatsDocument,
      {}
    )) as import("../../shared/generated/graphql").BlogStatsQuery;
    res.json(data.blog);
  } catch (error) {
    respondWithError(res, error, "Failed to fetch blog stats");
  }
});

// GET /api/stats/comment
router.get("/comment", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const data = (await client.request(
      CommentStatsDocument,
      {}
    )) as import("../../shared/generated/graphql").CommentStatsQuery;
    res.json(data.comments);
  } catch (error) {
    respondWithError(res, error, "Failed to fetch comment stats");
  }
});

export default router;
