-- 0017_institutional_membership.up.sql
--
-- Adds institutional membership tables and seeds the canonical DBIS member
-- directory.  The tier taxonomy comes from https://d-bis.org/members#tiers
-- with corrections per institutional review (2026-04).

-- Tier enum
DO $$ BEGIN
    CREATE TYPE institutional_tier AS ENUM (
        'sovereign_central_bank',
        'global_family_office',
        'settlement_member',
        'infrastructure_operator',
        'oversight_judicial',
        'delegated_authority',
        'standards_body'
    );
EXCEPTION WHEN duplicate_object THEN NULL;
END $$;

-- Members directory
CREATE TABLE IF NOT EXISTS institutional_members (
    id              SERIAL PRIMARY KEY,
    slug            VARCHAR(64)  NOT NULL UNIQUE,
    abbreviation    VARCHAR(16)  NOT NULL,
    name            TEXT         NOT NULL,
    tier            institutional_tier NOT NULL,
    description     TEXT         NOT NULL DEFAULT '',
    jurisdiction    TEXT,
    lei             VARCHAR(20),
    latitude        DOUBLE PRECISION,
    longitude       DOUBLE PRECISION,
    map_label       TEXT,
    active          BOOLEAN      NOT NULL DEFAULT TRUE,
    created_at      TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at      TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_institutional_members_tier   ON institutional_members(tier);
CREATE INDEX IF NOT EXISTS idx_institutional_members_active ON institutional_members(active);

-- Junction: wallet addresses linked to institutional members
CREATE TABLE IF NOT EXISTS institutional_member_wallets (
    id          SERIAL PRIMARY KEY,
    member_id   INTEGER NOT NULL REFERENCES institutional_members(id) ON DELETE CASCADE,
    address     VARCHAR(42) NOT NULL,
    label       TEXT,
    active      BOOLEAN NOT NULL DEFAULT TRUE,
    created_at  TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE(member_id, address)
);

CREATE INDEX IF NOT EXISTS idx_imw_address   ON institutional_member_wallets(address);
CREATE INDEX IF NOT EXISTS idx_imw_member_id ON institutional_member_wallets(member_id);

-- Triggers
CREATE TRIGGER update_institutional_members_updated_at
    BEFORE UPDATE ON institutional_members
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- ============================================================
-- Seed data — canonical member directory
-- ============================================================
-- Corrections from 2026-04 review:
--   • MLFO is a Global Family Office, NOT a central bank
--   • BIS Innovation Hub removed from directory entirely
--   • Added: ICCC, SAID, PANDA, Order of Hospitallers (XOM)
--   • Placeholder rows for BRICS founding central banks

INSERT INTO institutional_members
    (slug, abbreviation, name, tier, description, jurisdiction, lei, latitude, longitude, map_label)
VALUES
    -- Existing (corrected)
    ('omnl', 'OMNL', 'Organisation Mondiale du Numérique',
     'sovereign_central_bank',
     'Participating central bank — OMNL Head Office ledger and journal operator (Fineract / OMNL tenant). ARIN OrgId: OMNL.',
     'International / participating monetary union', '98450070C57395F6B906',
     39.61, -104.89, 'Greenwood Village, CO'),

    ('mlfo', 'MLFO', 'Mann Li Family Office',
     'global_family_office',
     'Founding family office (L.P.B.C., Colorado Entity 20241969162). Capital structure sponsor and BIS debit performance beneficiary. Registered agent: Pandora C. Walker.',
     'US-CO (Colorado)', NULL,
     40.02, -105.27, 'Boulder, CO'),

    ('defi-oracle', 'DFO', 'DeFi Oracle',
     'infrastructure_operator',
     'Infrastructure operator for Chain 138 ecosystem. Manages smart contract deployment (131 contracts), cross-chain bridges, PMM pools, and wallet integrations (MetaMask Snap, Ledger Live).',
     'US-CO (Colorado)', NULL,
     39.61, -104.89, 'Greenwood Village, CO'),

    -- Added entities
    ('iccc', 'ICCC', 'International Criminal Court of Commerce',
     'oversight_judicial',
     'International court with oversight authority over DBIS ecosystem commercial disputes and enforcement.',
     'International', NULL,
     NULL, NULL, NULL),

    ('said', 'SAID', 'SAID',
     'standards_body',
     'Standards and identity body within the DBIS institutional framework.',
     'International', NULL,
     NULL, NULL, NULL),

    ('panda', 'PANDA', 'PANDA',
     'standards_body',
     'Standards and coordination body within the DBIS institutional framework.',
     'International', NULL,
     NULL, NULL, NULL),

    ('xom', 'XOM', 'Sovereign Military Hospitaller Order of St. John of Jerusalem of Rhodes and of Malta',
     'delegated_authority',
     'The sovereign entity (Order of Hospitallers) extending DBIS the agency authority under which it operates. Recognised UN observer state.',
     'International (Rome)', NULL,
     41.90, 12.48, 'Rome, Italy'),

    -- BRICS founding member central banks (representative set)
    ('cb-brazil', 'BCB', 'Banco Central do Brasil',
     'sovereign_central_bank',
     'Central Bank of Brazil — BRICS founding member.',
     'Brazil', NULL,
     -15.79, -47.88, 'Brasília, Brazil'),

    ('cb-russia', 'CBR', 'Central Bank of the Russian Federation',
     'sovereign_central_bank',
     'Bank of Russia — BRICS founding member.',
     'Russia', NULL,
     55.76, 37.62, 'Moscow, Russia'),

    ('cb-india', 'RBI', 'Reserve Bank of India',
     'sovereign_central_bank',
     'Reserve Bank of India — BRICS founding member.',
     'India', NULL,
     18.93, 72.83, 'Mumbai, India'),

    ('cb-china', 'PBOC', 'People''s Bank of China',
     'sovereign_central_bank',
     'People''s Bank of China — BRICS founding member.',
     'China', NULL,
     39.91, 116.39, 'Beijing, China'),

    ('cb-south-africa', 'SARB', 'South African Reserve Bank',
     'sovereign_central_bank',
     'South African Reserve Bank — BRICS founding member.',
     'South Africa', NULL,
     -25.75, 28.19, 'Pretoria, South Africa'),

    -- BRICS expanded members (2024+)
    ('cb-egypt', 'CBE', 'Central Bank of Egypt',
     'sovereign_central_bank',
     'Central Bank of Egypt — BRICS member (2024).',
     'Egypt', NULL,
     30.04, 31.24, 'Cairo, Egypt'),

    ('cb-ethiopia', 'NBE', 'National Bank of Ethiopia',
     'sovereign_central_bank',
     'National Bank of Ethiopia — BRICS member (2024).',
     'Ethiopia', NULL,
     9.02, 38.75, 'Addis Ababa, Ethiopia'),

    ('cb-iran', 'CBI', 'Central Bank of the Islamic Republic of Iran',
     'sovereign_central_bank',
     'Central Bank of Iran — BRICS member (2024).',
     'Iran', NULL,
     35.70, 51.42, 'Tehran, Iran'),

    ('cb-uae', 'CBUAE', 'Central Bank of the UAE',
     'sovereign_central_bank',
     'Central Bank of the UAE — BRICS member (2024).',
     'United Arab Emirates', NULL,
     24.45, 54.65, 'Abu Dhabi, UAE'),

    ('cb-saudi-arabia', 'SAMA', 'Saudi Central Bank',
     'sovereign_central_bank',
     'Saudi Central Bank (formerly SAMA) — BRICS member (2024).',
     'Saudi Arabia', NULL,
     24.71, 46.68, 'Riyadh, Saudi Arabia')
ON CONFLICT (slug) DO NOTHING;
