-- Email verification tokens (single-use, 24 h).
-- Mirrors the password_resets shape already in prod.
-- Backfill grandfathers all existing users as verified so the Task C
-- sign-in gate does not lock out accounts created before this migration.

CREATE TABLE IF NOT EXISTS email_verifications (
  id          uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id     uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  token       text NOT NULL UNIQUE,
  expires_at  timestamptz NOT NULL,
  used_at     timestamptz,
  created_at  timestamptz NOT NULL DEFAULT now()
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS email_verifications_token_idx
  ON email_verifications(token);
--> statement-breakpoint
-- Grandfather every existing user as verified.
UPDATE users SET email_verified = now() WHERE email_verified IS NULL;
--> statement-breakpoint
GRANT ALL ON email_verifications TO tia_app;
