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

export const user = sqliteTable('user', {
	id: text('id').primaryKey(),
	firstName: text('first_name'),
	lastName: text('last_name'),
	email: text('email').unique(),
	passwordHash: text('password_hash'),
	appleId: text('apple_id').unique(),
	googleId: text('google_id').unique(),
	isPrivate: integer('is_private', { mode: 'boolean' }).default(false)
});

export const session = sqliteTable('session', {
	id: text('id').primaryKey(),
	userId: text('user_id').notNull().references(() => user.id),
	expiresAt: integer('expires_at', { mode: 'timestamp' }).notNull()
});

export type Session = typeof session.$inferSelect;

export type User = typeof user.$inferSelect;

export const dailyVerses = sqliteTable('daily_verses', {
	id: text('id').primaryKey(),
	date: text('date').unique().notNull(),
	bookId: text('book_id').notNull(),
	verseText: text('verse_text').notNull(),
	reference: text('reference').notNull(),
	createdAt: integer('created_at', { mode: 'timestamp' }),
});

export type DailyVerse = typeof dailyVerses.$inferSelect;

export const dailyCompletions = sqliteTable('daily_completions', {
	id: text('id').primaryKey(),
	anonymousId: text('anonymous_id').notNull(),
	date: text('date').notNull(),
	guessCount: integer('guess_count').notNull(),
	guesses: text('guesses'), // nullable; only stored for logged-in users
	completedAt: integer('completed_at', { mode: 'timestamp' }).notNull(),
}, (table) => [
	index('anonymous_id_date_idx').on(table.anonymousId, table.date),
	index('date_idx').on(table.date),
	index('date_guess_idx').on(table.date, table.guessCount),
	// Ensures schema matches the database migration and prevents duplicate submissions
	unique('daily_completions_anonymous_id_date_unique').on(table.anonymousId, table.date),
]);

export type DailyCompletion = typeof dailyCompletions.$inferSelect;

export const verseSubmissions = sqliteTable('verse_submissions', {
	id: text('id').primaryKey(),
	// Nullable so ON DELETE SET NULL can clear attribution when a user is deleted;
	// the scheduled verse still plays out (canonical text lives on daily_verses).
	userId: text('user_id').references(() => user.id, { onDelete: 'set null' }),
	scheduledDate: text('scheduled_date').notNull().unique(),
	selectedBookId: text('selected_book_id').notNull(),
	selectedChapter: integer('selected_chapter').notNull(),
	selectedVerse: integer('selected_verse').notNull(),
	// Raw integer of server UTC milliseconds — drives the 7-day rolling cooldown.
	submittedAt: integer('submitted_at').notNull(),
}, (table) => [
	index('verse_submissions_user_id_idx').on(table.userId),
]);

export type VerseSubmission = typeof verseSubmissions.$inferSelect;
