-- Migration: 007_BankConnections
-- Description: Create bank connection read models table for Open Banking integration

CREATE TABLE IF NOT EXISTS bank_connection_read_models (
    aggregate_id TEXT PRIMARY KEY,
    company_id TEXT NOT NULL,
    aspsp_name TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'initiated',
    session_id TEXT,
    valid_until TIMESTAMPTZ,
    accounts_json TEXT,
    failure_reason TEXT,
    create_time TIMESTAMPTZ NOT NULL,
    updated_time TIMESTAMPTZ NOT NULL,
    last_aggregate_sequence_number INT NOT NULL
);

-- Index for efficient queries by company
CREATE INDEX IF NOT EXISTS idx_bank_connection_company
    ON bank_connection_read_models(company_id);

-- Index for efficient queries by company and status
CREATE INDEX IF NOT EXISTS idx_bank_connection_company_status
    ON bank_connection_read_models(company_id, status);

-- Index for finding active connections (established and not expired)
CREATE INDEX IF NOT EXISTS idx_bank_connection_active
    ON bank_connection_read_models(company_id, status, valid_until)
    WHERE status = 'established';

COMMENT ON TABLE bank_connection_read_models IS 'Bank connections via Enable Banking Open Banking API';
COMMENT ON COLUMN bank_connection_read_models.status IS 'initiated = OAuth started, established = active connection, failed = authorization failed, disconnected = user disconnected';
COMMENT ON COLUMN bank_connection_read_models.accounts_json IS 'JSON array of available bank accounts from the connection';
COMMENT ON COLUMN bank_connection_read_models.session_id IS 'Enable Banking session ID - used for API calls (not exposed to client)';
