CREATE TABLE users (
  id TEXT PRIMARY KEY NOT NULL UNIQUE,
  username VARCHAR(255)
);

CREATE TABLE passkeys (
  id TEXT PRIMARY KEY NOT NULL UNIQUE,
  public_key BYTEA,
  webauthn_user__id TEXT UNIQUE,
  counter BIGINT,
  device_type VARCHAR(32),
  transports VARCHAR(255)
);

-- User/passkey junction table
CREATE TABLE user_passkeys (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id TEXT NOT NULL,
  passkey_id TEXT NOT NULL,

  -- Foreign key constraints
  CONSTRAINT fk_user_passkeys_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_user_passkeys_passkeys FOREIGN KEY (passkey_id) REFERENCES passkeys(id) ON DELETE CASCADE,

  -- Prevent duplicates
  CONSTRAINT unique_user_passkeys UNIQUE (user_id, passkey_id)
);

CREATE INDEX index_passkeys ON passkeys (id, webauthn_user__id);
