import { boolean, index, jsonb, timestamp, varchar } from "drizzle-orm/pg-core";
import { createId, createTable } from "./schema-utils";
import { JSONContent } from "novel";
import { relations, sql } from "drizzle-orm";
import { categories, Category } from "./category";
import { users } from "./auth";
import { Comment, comments } from "./comments";
import { PublicUser } from ".";

export const articles = createTable(
  "article",
  {
    id: varchar("id", { length: 255 })
      .primaryKey()
      .$defaultFn(() => createId())
      .notNull(),
    title: varchar("title", { length: 256 }).notNull(),
    slug: varchar("slug", { length: 256 }).unique().notNull(),
    authorId: varchar("author_id", { length: 255 }),
    content: jsonb("content").$type<JSONContent>(),
    categoryId: varchar("category_id", { length: 255 }),
    published: boolean("published").default(false),
    createdAt: timestamp("created_at", { withTimezone: true })
      .default(sql`CURRENT_TIMESTAMP`)
      .notNull(),
    updatedAt: timestamp("updated_at", { withTimezone: true }).$onUpdate(
      () => new Date(),
    ),
  },
  (example) => ({
    titleIndex: index("article_title_idx").on(example.title),
    slugIndex: index("article_slug_idx").on(example.slug),
    createdAtIndex: index("article_created_at_idx").on(example.createdAt),
  }),
);

export const articleRelations = relations(articles, ({ one, many }) => ({
  category: one(categories, {
    fields: [articles.categoryId],
    references: [categories.id],
  }),
  author: one(users, {
    fields: [articles.authorId],
    references: [users.id],
  }),
  comments: many(comments),
}));

export type Article = typeof articles.$inferSelect & {
  author?: PublicUser;
  category?: Category;
  comments?: Array<Comment>;
};
