-- App Banners Table for dynamic hero content on home page

CREATE TABLE IF NOT EXISTS app_banners (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    title TEXT NOT NULL,
    image_url TEXT NOT NULL,  -- 16:9 Banner Image
    link_target TEXT,         -- e.g., '/sessions'
    cta_text TEXT DEFAULT 'Open',
    is_active BOOLEAN DEFAULT false,
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now()
);

-- Only one banner should be active at a time (optional constraint)
CREATE UNIQUE INDEX IF NOT EXISTS idx_app_banners_active 
    ON app_banners (is_active) 
    WHERE is_active = true;

-- RLS Policies
ALTER TABLE app_banners ENABLE ROW LEVEL SECURITY;

-- Everyone can view active banners
CREATE POLICY "Anyone can view active banners"
    ON app_banners FOR SELECT
    USING (is_active = true);

-- Admins can manage all banners
CREATE POLICY "Admins can manage banners"
    ON app_banners FOR ALL
    USING (
        EXISTS (
            SELECT 1 FROM admin_users
            WHERE admin_users.user_id = auth.uid()
        )
    );

-- Trigger for updated_at
CREATE OR REPLACE FUNCTION update_app_banners_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = now();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trigger_app_banners_updated_at
    BEFORE UPDATE ON app_banners
    FOR EACH ROW
    EXECUTE FUNCTION update_app_banners_updated_at();
