-- AZ-537 (Epic AZ-530, CMMC AC.L2-3.1.8): account lockout + audit events.
-- Adds the per-row state used by UserService.ValidateUser to enforce a 10-failure
-- consecutive-attempt lockout, plus a generic audit_events table that the per-account
-- sliding-window rate-limit reads. The audit table is also reused by future security
-- events (login_success, lockout_release, etc.).

ALTER TABLE public.users
    ADD COLUMN IF NOT EXISTS failed_login_count int       NOT NULL DEFAULT 0,
    ADD COLUMN IF NOT EXISTS lockout_until      timestamp NULL;

CREATE TABLE IF NOT EXISTS public.audit_events
(
    id          bigserial    PRIMARY KEY,
    event_type  varchar(64)  NOT NULL,
    occurred_at timestamp    NOT NULL DEFAULT now(),
    email       varchar(160) NULL,
    ip          varchar(64)  NULL,
    metadata    text         NULL
);

CREATE INDEX IF NOT EXISTS audit_events_event_type_email_idx
    ON public.audit_events (event_type, email, occurred_at DESC);

GRANT INSERT, SELECT ON public.audit_events TO azaion_admin;
GRANT SELECT          ON public.audit_events TO azaion_reader;
GRANT USAGE, SELECT   ON SEQUENCE public.audit_events_id_seq TO azaion_admin;
