-- Metadata DB Initialization for Baron SSO
-- Purpose: Manage Relying Parties (RP) and User Consent

-- 1. Relying Parties (RP) Table
CREATE TABLE IF NOT EXISTS relying_parties (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    client_id VARCHAR(255) NOT NULL UNIQUE,
    client_secret VARCHAR(255) NOT NULL,
    name VARCHAR(255) NOT NULL,
    redirect_uris TEXT[] NOT NULL,
    description TEXT,
    logo_url VARCHAR(2048),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- 2. User Consents Table
-- Tracks which scopes/permissions a user has granted to an RP
CREATE TABLE IF NOT EXISTS user_consents (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id VARCHAR(255) NOT NULL, -- Subject ID from IDP
    rp_id UUID NOT NULL REFERENCES relying_parties(id),
    scopes TEXT[] NOT NULL,
    granted_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    revoked_at TIMESTAMP WITH TIME ZONE,
    UNIQUE(user_id, rp_id)
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_rp_client_id ON relying_parties(client_id);
CREATE INDEX IF NOT EXISTS idx_consent_user ON user_consents(user_id);

-- 3. Seed Data (Optional)
-- Initial RP for testing purposes
INSERT INTO relying_parties (client_id, client_secret, name, redirect_uris, description)
VALUES (
    'baron-admin-client',
    'secret-key-12345',
    'Baron Admin Console',
    ARRAY['http://localhost:5000/callback', 'https://sso.hmac.kr/callback'],
    'Official Admin Console for Baron SSO'
) ON CONFLICT (client_id) DO NOTHING;