import {
  index,
  integer,
  jsonb,
  primaryKey,
  timestamp,
  varchar,
} from "drizzle-orm/pg-core";
import { Article, articles } from "./article";
import { JSONContent } from "novel";
import { relations, sql } from "drizzle-orm";
import { createId, createTable } from "./schema-utils";
import { users } from "./auth";
import { PublicUser } from ".";

export const comments = createTable(
  "comment",
  {
    id: varchar("id", { length: 255 })
      .primaryKey()
      .$defaultFn(() => createId())
      .notNull(),
    articleId: varchar("article_id", { length: 255 })
      .notNull()
      .references(() => articles.id),
    authorId: varchar("author_id", { length: 255 })
      .notNull()
      .references(() => users.id),
    parentId: varchar("parent_id", { length: 255 }),
    content: jsonb("content").$type<JSONContent>(),
    createdAt: timestamp("created_at", { withTimezone: true })
      .default(sql`CURRENT_TIMESTAMP`)
      .notNull(),
    updatedAt: timestamp("updated_at", { withTimezone: true }).$onUpdate(
      () => new Date(),
    ),
  },
  (example) => ({
    articleIdIndex: index("comment_article_id_idx").on(example.articleId),
    authorIdIndex: index("comment_author_id_idx").on(example.authorId),
    createdAtIndex: index("comment_created_at_idx").on(example.createdAt),
  }),
);

export const commentsRelations = relations(comments, ({ many, one }) => ({
  article: one(articles, {
    fields: [comments.articleId],
    references: [articles.id],
  }),
  author: one(users, {
    fields: [comments.authorId],
    references: [users.id],
  }),
  // comments: many(comments),
}));

export type Comment = typeof comments.$inferSelect & {
  article?: Article;
  author?: PublicUser;
};

export type CommentNode = Comment & {
  children: CommentNode[];
};

export const commentVotes = createTable(
  "comment_vote",
  {
    vote: integer("vote").notNull().$type<1 | -1>().default(1),
    commentId: varchar("comment_id", {
      length: 255,
    })
      .references(() => comments.id)
      .notNull(),
    userId: varchar("user_id", {
      length: 255,
    })
      .references(() => users.id)
      .notNull(),
  },
  (example) => ({
    comboundKey: primaryKey({
      columns: [example.commentId, example.userId],
    }),
  }),
);
