CREATE TABLE IF NOT EXISTS integration_api_keys (
    id BIGSERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    environment VARCHAR(50) NOT NULL,
    status VARCHAR(20) NOT NULL DEFAULT 'active',
    key_prefix VARCHAR(64) NOT NULL,
    key_hash TEXT NOT NULL,
    permission_codes JSONB NOT NULL DEFAULT '[]'::jsonb,
    all_area BOOLEAN NOT NULL DEFAULT FALSE,
    area_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
    all_location BOOLEAN NOT NULL DEFAULT FALSE,
    location_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
    last_used_at TIMESTAMPTZ NULL,
    last_used_from VARCHAR(128) NULL,
    revoked_at TIMESTAMPTZ NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMPTZ NULL,
    CONSTRAINT uq_integration_api_keys_environment_prefix UNIQUE (environment, key_prefix)
);

CREATE INDEX idx_integration_api_keys_status ON integration_api_keys (status);
CREATE INDEX idx_integration_api_keys_deleted_at ON integration_api_keys (deleted_at);
