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

export const registration = sqliteTable(
	"registration",
	{
		id: text("id").primaryKey(),
		firstName: text("first_name").notNull(),
		lastName: text("last_name").notNull(),
		email: text("email").notNull(),
		phone: text("phone"),
		// registrationType: 'performer' | 'watcher'
		registrationType: text("registration_type").notNull().default("watcher"),
		// Performer-specific fields
		artForm: text("art_form"),
		experience: text("experience"),
		isOver16: integer("is_over_16", { mode: "boolean" })
			.notNull()
			.default(false),
		// Watcher-specific fields
		drinkCardValue: integer("drink_card_value").default(0),
		// Guests: JSON array of {firstName, lastName, email?, phone?} objects
		guests: text("guests"),
		// Contact / demographic
		postcode: text("postcode"),
		birthdate: text("birthdate"),
		// Shared
		extraQuestions: text("extra_questions"),
		managementToken: text("management_token").unique(),
		cancelledAt: integer("cancelled_at", { mode: "timestamp_ms" }),
		// Payment fields
		paymentStatus: text("payment_status").notNull().default("pending"),
		paymentAmount: integer("payment_amount").default(0),
		giftAmount: integer("gift_amount").default(0),
		lemonsqueezyOrderId: text("lemonsqueezy_order_id"),
		lemonsqueezyCustomerId: text("lemonsqueezy_customer_id"),
		paidAt: integer("paid_at", { mode: "timestamp_ms" }),
		// Set when the drinkCardValue has been credited to the user's drinkkaart.
		// Null means not yet credited (either unpaid, account doesn't exist yet, or
		// the registration is a performer). Used to prevent double-crediting.
		drinkkaartCreditedAt: integer("drinkkaart_credited_at", {
			mode: "timestamp_ms",
		}),
		createdAt: integer("created_at", { mode: "timestamp_ms" })
			.default(sql`(cast(unixepoch('subsecond') * 1000 as integer))`)
			.notNull(),
	},
	(table) => [
		index("registration_email_idx").on(table.email),
		index("registration_registrationType_idx").on(table.registrationType),
		index("registration_artForm_idx").on(table.artForm),
		index("registration_createdAt_idx").on(table.createdAt),
		index("registration_managementToken_idx").on(table.managementToken),
		index("registration_paymentStatus_idx").on(table.paymentStatus),
		index("registration_giftAmount_idx").on(table.giftAmount),
		index("registration_lemonsqueezyOrderId_idx").on(table.lemonsqueezyOrderId),
	],
);
