-- API Keys table for programmatic access authentication
CREATE TABLE IF NOT EXISTS apikey_read_models (
    aggregate_id VARCHAR(255) PRIMARY KEY,
    create_time TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_time TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    last_aggregate_sequence_number INT NOT NULL DEFAULT 1,

    name VARCHAR(255) NOT NULL,
    key_hash VARCHAR(64) NOT NULL,
    company_id VARCHAR(255) NOT NULL,
    created_by VARCHAR(255) NOT NULL,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    revoked_time TIMESTAMPTZ,
    revoked_by VARCHAR(255)
);

-- Index for looking up API keys by company
CREATE INDEX IF NOT EXISTS idx_apikey_company ON apikey_read_models(company_id);

-- Partial index for efficient lookups of active API keys
CREATE INDEX IF NOT EXISTS idx_apikey_active ON apikey_read_models(aggregate_id) WHERE is_active = true;
