-- ============================================
-- TEMPLATE-SAAS: Tenant Settings Table
-- Schema: tenants
-- Version: 1.0.0
-- ============================================

-- For structured settings that need to be queried
CREATE TABLE tenants.tenant_settings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES tenants.tenants(id) ON DELETE CASCADE,

    -- Setting identification
    category VARCHAR(100) NOT NULL,  -- 'general', 'billing', 'notifications', 'security'
    key VARCHAR(100) NOT NULL,

    -- Value (supports different types)
    value_string VARCHAR(1000),
    value_number DECIMAL(20, 4),
    value_boolean BOOLEAN,
    value_json JSONB,

    -- Metadata
    description TEXT,
    is_sensitive BOOLEAN DEFAULT FALSE,  -- For encryption at rest

    -- Audit
    created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,
    updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,
    updated_by UUID,

    -- Constraints
    CONSTRAINT unique_tenant_setting UNIQUE (tenant_id, category, key)
);

-- Indexes
CREATE INDEX idx_tenant_settings_tenant ON tenants.tenant_settings(tenant_id);
CREATE INDEX idx_tenant_settings_category ON tenants.tenant_settings(tenant_id, category);

-- RLS
ALTER TABLE tenants.tenant_settings ENABLE ROW LEVEL SECURITY;

CREATE POLICY tenant_settings_isolation ON tenants.tenant_settings
    USING (tenant_id = current_setting('app.current_tenant_id', true)::UUID);

-- Trigger for updated_at
CREATE TRIGGER trg_tenant_settings_updated_at
    BEFORE UPDATE ON tenants.tenant_settings
    FOR EACH ROW
    EXECUTE FUNCTION tenants.update_updated_at();

-- Comments
COMMENT ON TABLE tenants.tenant_settings IS 'Structured tenant settings for queryable configuration';
COMMENT ON COLUMN tenants.tenant_settings.is_sensitive IS 'Flag for values that should be encrypted at rest';
