import { pgTable, serial, text, timestamp, integer } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';

export const words = pgTable('words', {
  id: serial('id').primaryKey(),
  hindi: text('hindi').notNull(),
  english: text('english').notNull(),
  note: text('note'),
  createdAt: timestamp('created_at').notNull().defaultNow(),
  updatedAt: timestamp('updated_at').notNull().defaultNow(),
});

export const examples = pgTable('examples', {
  id: serial('id').primaryKey(),
  wordId: serial('word_id').notNull().references(() => words.id, { onDelete: 'cascade' }),
  hindi: text('hindi').notNull(),
  english: text('english').notNull(),
  note: text('note'),
});

export const tags = pgTable('tags', {
  id: serial('id').primaryKey(),
  name: text('name').notNull().unique(),
  description: text('description'),
  level: text('level').notNull(), // 'page', 'subheading', 'grammar', 'gender'
  parentPageId: integer('parent_page_id'), // For subheadings, references the parent page tag (FK constraint in migration)
});

export const wordTags = pgTable('word_tags', {
  id: serial('id').primaryKey(),
  wordId: serial('word_id').notNull().references(() => words.id, { onDelete: 'cascade' }),
  tagId: serial('tag_id').notNull().references(() => tags.id),
});

export const seeAlso = pgTable('see_also', {
  id: serial('id').primaryKey(),
  wordId: serial('word_id').notNull().references(() => words.id, { onDelete: 'cascade' }),
  reference: text('reference').notNull(), // Link text like "[चीज़](#चीज़)" or "[Reflexive verbs](/grammar/reflexive-verbs)"
  note: text('note'), // Optional additional context
});

// Relations
export const wordsRelations = relations(words, ({ many }) => ({
  examples: many(examples),
  tags: many(wordTags),
  seeAlso: many(seeAlso),
}));

export const examplesRelations = relations(examples, ({ one }) => ({
  word: one(words, {
    fields: [examples.wordId],
    references: [words.id],
  }),
}));

export const tagsRelations = relations(tags, ({ many }) => ({
  words: many(wordTags),
}));

export const wordTagsRelations = relations(wordTags, ({ one }) => ({
  word: one(words, {
    fields: [wordTags.wordId],
    references: [words.id],
  }),
  tag: one(tags, {
    fields: [wordTags.tagId],
    references: [tags.id],
  }),
}));

export const seeAlsoRelations = relations(seeAlso, ({ one }) => ({
  word: one(words, {
    fields: [seeAlso.wordId],
    references: [words.id],
  }),
}));

// Inferred types from schema
export type DBWord = typeof words.$inferSelect;
export type DBExample = typeof examples.$inferSelect;
export type DBTag = typeof tags.$inferSelect;
export type DBSeeAlso = typeof seeAlso.$inferSelect;
