-- ============================================================================
-- V004: 감사로그 + 접근 이력
-- ============================================================================

-- ----------------------------------------------------------------------------
-- 감사로그 (의사결정 액션 - @Auditable AOP가 기록)
-- ----------------------------------------------------------------------------
CREATE TABLE kcg.auth_audit_log (
    audit_sn        BIGSERIAL PRIMARY KEY,
    user_id         UUID,
    user_acnt       VARCHAR(50),
    action_cd       VARCHAR(50) NOT NULL,               -- LOGIN, LOGOUT, CONFIRM_PARENT, REJECT_PARENT, EXCLUDE_CANDIDATE, LABEL_CREATE, ROLE_GRANT, PERM_UPDATE, USER_CREATE, ...
    resource_type   VARCHAR(50),                        -- VESSEL, GROUP, PARENT_INFERENCE, USER, ROLE, SYSTEM
    resource_id     VARCHAR(100),
    detail          JSONB,
    ip_address      VARCHAR(45),
    result          VARCHAR(20),                        -- SUCCESS, FAILED
    fail_reason     TEXT,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idx_audit_user ON kcg.auth_audit_log(user_id, created_at DESC);
CREATE INDEX idx_audit_action ON kcg.auth_audit_log(action_cd, created_at DESC);
CREATE INDEX idx_audit_resource ON kcg.auth_audit_log(resource_type, resource_id);
CREATE INDEX idx_audit_created ON kcg.auth_audit_log(created_at DESC);

COMMENT ON TABLE kcg.auth_audit_log IS '감사로그 (운영자 의사결정 + 시스템 액션)';

-- ----------------------------------------------------------------------------
-- 접근 이력 (모든 HTTP 요청 - AccessLogFilter가 기록)
-- ----------------------------------------------------------------------------
CREATE TABLE kcg.auth_access_log (
    access_sn       BIGSERIAL PRIMARY KEY,
    user_id         UUID,
    user_acnt       VARCHAR(50),
    http_method     VARCHAR(10),
    request_path    VARCHAR(500),
    query_string    TEXT,
    status_code     INT,
    duration_ms     INT,
    ip_address      VARCHAR(45),
    user_agent      TEXT,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idx_access_user ON kcg.auth_access_log(user_id, created_at DESC);
CREATE INDEX idx_access_path ON kcg.auth_access_log(request_path, created_at DESC);
CREATE INDEX idx_access_created ON kcg.auth_access_log(created_at DESC);

COMMENT ON TABLE kcg.auth_access_log IS '접근 이력 (모든 HTTP 요청)';
