alter table identity.users
  add column if not exists two_factor_enabled boolean not null default false;

create table if not exists identity.two_factors (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null unique references identity.users(id) on delete cascade,
  secret text not null,
  backup_codes text not null,
  verified boolean not null default false,
  failed_verification_count integer not null default 0 check (failed_verification_count >= 0),
  locked_until timestamptz
);

create index if not exists identity_two_factors_locked_until_idx
  on identity.two_factors (locked_until)
  where locked_until is not null;

revoke all on table identity.two_factors
from public, app_runtime, admin_runtime, backup_reader, migration_runner;

grant select, insert, update, delete on table identity.two_factors
to identity_runtime;
