import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core';
import { relations } from 'drizzle-orm';

export const words = sqliteTable('words', {
  id: integer('id').primaryKey({ autoIncrement: true }),
  hindi: text('hindi').notNull(),
  english: text('english').notNull(),
  type: text('type'), // noun, verb, adjective, etc.
  gender: text('gender'), // m, f, or null
  note: text('note'),
  createdAt: integer('created_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date()),
  updatedAt: integer('updated_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date()),
});

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

export const tags = sqliteTable('tags', {
  id: integer('id').primaryKey({ autoIncrement: true }),
  name: text('name').notNull().unique(),
  description: text('description'),
});

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

export const seeAlso = sqliteTable('see_also', {
  id: integer('id').primaryKey({ autoIncrement: true }),
  wordId: integer('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;
