-- Migration 000006: Users table for internal user management (E3-08).
-- Users in Keycloak are the authoritative source for authentication.
-- This table stores per-tenant user metadata (department, role, status)
-- managed via the admin API. Keycloak sub is used as external reference.

CREATE TABLE IF NOT EXISTS users (
    id          UUID        PRIMARY KEY DEFAULT uuid_generate_v4(),
    tenant_id   TEXT        NOT NULL,
    email       TEXT        NOT NULL,
    name        TEXT        NOT NULL,
    department  TEXT,
    role        TEXT        NOT NULL DEFAULT 'user'
                            CHECK (role IN ('admin','manager','user','auditor')),
    is_active   BOOLEAN     NOT NULL DEFAULT TRUE,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(tenant_id, email)
);

CREATE INDEX IF NOT EXISTS idx_users_tenant ON users(tenant_id, is_active);
