import { index, text, timestamp, varchar } from "drizzle-orm/pg-core";
import { createId, createTable } from "./schema-utils";
import { relations, sql } from "drizzle-orm";
import { Article, articles } from "./article";

export const categories = createTable(
  "category",
  {
    id: varchar("id", { length: 255 })
      .primaryKey()
      .$defaultFn(() => createId())
      .notNull(),
    name: varchar("name", { length: 256 }).notNull(),
    description: text("description"),
    slug: varchar("slug", { length: 256 }).unique().notNull(),

    image: varchar("image", { length: 255 }),
    createdAt: timestamp("created_at", { withTimezone: true })
      .default(sql`CURRENT_TIMESTAMP`)
      .notNull(),
    updatedAt: timestamp("updated_at", { withTimezone: true }).$onUpdate(
      () => new Date(),
    ),
  },
  (example) => ({
    nameIndex: index("category_name_idx").on(example.name),
    slugameIndex: index("category_slug_idx").on(example.slug),
    createdAtIndex: index("category_created_at_idx").on(example.createdAt),
  }),
);
export type Category = typeof categories.$inferSelect & {
  articles?: Article[];
};

export const categoryRelations = relations(categories, ({ many }) => ({
  articles: many(articles),
}));
