import { builder } from "../builder";
import { ArticleType } from "../types/index";
import { articles, users } from "../../db/schema/index";
import { eq, and, lte, desc } from "drizzle-orm";

builder.queryField("articles", (t) =>
  t.field({
    type: [ArticleType],
    args: {
      featured: t.arg.boolean(),
      limit: t.arg.int(),
    },
    resolve: async (_root, args, ctx) => {
      let query = ctx.db
        .select()
        .from(articles)
        .where(lte(articles.publish_date, new Date()))
        .orderBy(desc(articles.publish_date));

      if (args.limit) {
        query = (query as any).limit(args.limit);
      }

      const articleList = await query;

      return Promise.all(
        articleList.map(async (article: any) => {
          let author = null;
          if (article.author) {
            const authorUser = await ctx.db
              .select({
                first_name: users.first_name,
                last_name: users.last_name,
                avatar: users.avatar,
                description: users.description,
              })
              .from(users)
              .where(eq(users.id, article.author))
              .limit(1);
            author = authorUser[0] || null;
          }
          return { ...article, author };
        }),
      );
    },
  }),
);

builder.queryField("article", (t) =>
  t.field({
    type: ArticleType,
    nullable: true,
    args: {
      slug: t.arg.string({ required: true }),
    },
    resolve: async (_root, args, ctx) => {
      const article = await ctx.db
        .select()
        .from(articles)
        .where(and(eq(articles.slug, args.slug), lte(articles.publish_date, new Date())))
        .limit(1);

      if (!article[0]) return null;

      let author = null;
      if (article[0].author) {
        const authorUser = await ctx.db
          .select({
            first_name: users.first_name,
            last_name: users.last_name,
            avatar: users.avatar,
            description: users.description,
          })
          .from(users)
          .where(eq(users.id, article[0].author))
          .limit(1);
        author = authorUser[0] || null;
      }

      return { ...article[0], author };
    },
  }),
);
