import { pgTable, text, serial, timestamp, integer, varchar, boolean, primaryKey, uniqueIndex } from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { z } from "zod/v4";
import { usersTable } from "./users";

export const notesTable = pgTable("notes", {
  id: serial("id").primaryKey(),
  userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
  title: varchar("title", { length: 300 }).notNull().default(""),
  content: text("content").notNull().default(""),
  color: varchar("color", { length: 32 }).notNull().default("default"),
  isPinned: boolean("is_pinned").notNull().default(false),
  isArchived: boolean("is_archived").notNull().default(false),
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
  updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow().$onUpdate(() => new Date()),
});

export const noteLabelsTable = pgTable("note_labels", {
  id: serial("id").primaryKey(),
  userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
  name: varchar("name", { length: 80 }).notNull(),
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
}, (t) => ({
  userNameUnique: uniqueIndex("note_labels_user_name_unique").on(t.userId, t.name),
}));

export const noteLabelAssignmentsTable = pgTable("note_label_assignments", {
  noteId: integer("note_id").notNull().references(() => notesTable.id, { onDelete: "cascade" }),
  labelId: integer("label_id").notNull().references(() => noteLabelsTable.id, { onDelete: "cascade" }),
}, (t) => ({
  pk: primaryKey({ columns: [t.noteId, t.labelId] }),
}));

export const insertNoteSchema = createInsertSchema(notesTable).omit({ id: true, createdAt: true, updatedAt: true });
export type InsertNote = z.infer<typeof insertNoteSchema>;
export type Note = typeof notesTable.$inferSelect;

export const insertNoteLabelSchema = createInsertSchema(noteLabelsTable).omit({ id: true, createdAt: true });
export type InsertNoteLabel = z.infer<typeof insertNoteLabelSchema>;
export type NoteLabel = typeof noteLabelsTable.$inferSelect;
