-- WebAuthn device registrations for emiMobile
-- Run against the LEMS database.
-- Drop and recreate if upgrading from the UUID-based schema.

DROP TABLE IF EXISTS lems.device_registrations;

CREATE TABLE lems.device_registrations (
  id              SERIAL PRIMARY KEY,
  credential_id   TEXT          NOT NULL UNIQUE,
  device_name     VARCHAR(255),
  user_agent      TEXT,
  public_key_x    BYTEA         NOT NULL,
  public_key_y    BYTEA         NOT NULL,
  public_key_alg  INTEGER       NOT NULL DEFAULT -7,  -- -7 = ES256
  sign_count      BIGINT        NOT NULL DEFAULT 0,
  registered_at   TIMESTAMPTZ   DEFAULT NOW(),
  revoked_at      TIMESTAMPTZ,
  revoked_by      VARCHAR(255)
);

CREATE INDEX IF NOT EXISTS idx_device_reg_cred_id
  ON lems.device_registrations (credential_id);

COMMENT ON TABLE lems.device_registrations IS
  'WebAuthn (FIDO2) credential store for emiMobile device access control. '
  'credential_id is the base64url-encoded credential ID from navigator.credentials.create(). '
  'public_key_x/y are the raw 32-byte big-endian EC P-256 coordinates. '
  'sign_count is updated after each successful authentication assertion. '
  'Admins revoke access by setting revoked_at.';
