PRAGMA foreign_keys = ON;

-- Better Auth core schema. These four tables (user, session, account,
-- verification) are owned and written entirely by Better Auth — the app never
-- inserts into them directly; sign-up / sign-in / sessions all flow through the
-- generated `/api/auth/**` routes (see src/auth.ts).
--
-- The schema is generated by Better Auth's own migration generator
-- (`getMigrations(...).compileMigrations()`); the columns are spelled in
-- snake_case to match the rest of the app's DB convention. Better Auth is handed
-- the app's kysely (with CamelCasePlugin) in src/auth.ts, so its camelCase field
-- names (emailVerified, userId, createdAt, ...) compile to exactly these
-- snake_case columns at runtime. To change this schema (add a provider field, a
-- plugin table, ...), re-run the generator rather than hand-editing.
--
-- Email + password is the default sign-in method. The credential hash is stored
-- by Better Auth in account.password (provider_id = 'credential'), never on the
-- user row.
CREATE TABLE IF NOT EXISTS "user" (
  "id" text not null primary key,
  "name" text not null,
  "email" text not null unique,
  "email_verified" integer not null,
  "image" text,
  "created_at" date not null,
  "updated_at" date not null
);

CREATE TABLE IF NOT EXISTS "session" (
  "id" text not null primary key,
  "expires_at" date not null,
  "token" text not null unique,
  "created_at" date not null,
  "updated_at" date not null,
  "ip_address" text,
  "user_agent" text,
  "user_id" text not null references "user" ("id") on delete cascade
);

CREATE TABLE IF NOT EXISTS "account" (
  "id" text not null primary key,
  "account_id" text not null,
  "provider_id" text not null,
  "user_id" text not null references "user" ("id") on delete cascade,
  "access_token" text,
  "refresh_token" text,
  "id_token" text,
  "access_token_expires_at" date,
  "refresh_token_expires_at" date,
  "scope" text,
  "password" text,
  "created_at" date not null,
  "updated_at" date not null
);

CREATE TABLE IF NOT EXISTS "verification" (
  "id" text not null primary key,
  "identifier" text not null,
  "value" text not null,
  "expires_at" date not null,
  "created_at" date not null,
  "updated_at" date not null
);

CREATE INDEX IF NOT EXISTS "session_user_id_idx" ON "session" ("user_id");
CREATE INDEX IF NOT EXISTS "account_user_id_idx" ON "account" ("user_id");
CREATE INDEX IF NOT EXISTS "verification_identifier_idx" ON "verification" ("identifier");
