 -- =============================================================
-- Supabase Table Schema for Admin Rules
-- =============================================================
-- Run this SQL in your Supabase SQL Editor to create the admin_rules table
-- =============================================================

CREATE TABLE IF NOT EXISTS admin_rules (
    id BIGSERIAL PRIMARY KEY,
    tenant_id TEXT NOT NULL,
    rule TEXT NOT NULL,
    pattern TEXT,
    severity TEXT DEFAULT 'medium' CHECK (severity IN ('low', 'medium', 'high', 'critical')),
    description TEXT,
    enabled BOOLEAN DEFAULT true,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(tenant_id, rule)
);

-- Create index for faster tenant-based queries
CREATE INDEX IF NOT EXISTS idx_admin_rules_tenant_id ON admin_rules(tenant_id);
CREATE INDEX IF NOT EXISTS idx_admin_rules_enabled ON admin_rules(enabled);

-- Create index for faster lookups by tenant and enabled status
CREATE INDEX IF NOT EXISTS idx_admin_rules_tenant_enabled ON admin_rules(tenant_id, enabled);

-- Enable Row Level Security (RLS) - optional, adjust based on your needs
ALTER TABLE admin_rules ENABLE ROW LEVEL SECURITY;

-- Create policy to allow service role to access all rows
-- Adjust this policy based on your security requirements
CREATE POLICY "Service role can manage all admin rules"
    ON admin_rules
    FOR ALL
    USING (true)
    WITH CHECK (true);

-- Create a function to automatically update updated_at timestamp
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ language 'plpgsql';

-- Create trigger to automatically update updated_at
CREATE TRIGGER update_admin_rules_updated_at
    BEFORE UPDATE ON admin_rules
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();

-- =============================================================
-- Example queries to verify the table:
-- =============================================================
-- SELECT * FROM admin_rules WHERE tenant_id = 'your_tenant_id';
-- SELECT * FROM admin_rules WHERE enabled = true;
-- =============================================================

