-- Create sms_settings table
CREATE TABLE IF NOT EXISTS public.sms_settings (
    id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
    provider TEXT DEFAULT 'netgsm',
    api_url TEXT DEFAULT 'https://api.netgsm.com.tr/sms/send/get',
    username TEXT,
    password TEXT,
    header TEXT,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now())
);

-- Create sms_logs table
CREATE TABLE IF NOT EXISTS public.sms_logs (
    id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
    phone TEXT NOT NULL,
    message TEXT NOT NULL,
    status TEXT, -- 'success' or 'error'
    response_code TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now())
);

-- Enable RLS
ALTER TABLE public.sms_settings ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.sms_logs ENABLE ROW LEVEL SECURITY;

-- RLS Policies for sms_settings
-- Only admins can view settings
CREATE POLICY "Admins can view sms settings" ON public.sms_settings
    FOR SELECT
    USING (
        exists (
            select 1 from public.profiles
            where profiles.id = auth.uid()
            and profiles.role = 'admin'
        )
    );

-- Only admins can update settings
CREATE POLICY "Admins can update sms settings" ON public.sms_settings
    FOR UPDATE
    USING (
        exists (
            select 1 from public.profiles
            where profiles.id = auth.uid()
            and profiles.role = 'admin'
        )
    );

-- Only admins can insert settings (though usually init script does this)
CREATE POLICY "Admins can insert sms settings" ON public.sms_settings
    FOR INSERT
    WITH CHECK (
        exists (
            select 1 from public.profiles
            where profiles.id = auth.uid()
            and profiles.role = 'admin'
        )
    );

-- RLS Policies for sms_logs
-- Only admins can view logs
CREATE POLICY "Admins can view sms logs" ON public.sms_logs
    FOR SELECT
    USING (
        exists (
            select 1 from public.profiles
            where profiles.id = auth.uid()
            and profiles.role = 'admin'
        )
    );

-- System functionality (via Service Role) will bypass RLS, so we don't strictly need INSERT policies for user logic 
-- unless we want admins to manually insert logs (unlikely).
-- But for good measure, allow admins to delete logs if needed
CREATE POLICY "Admins can delete sms logs" ON public.sms_logs
    FOR DELETE
    USING (
        exists (
            select 1 from public.profiles
            where profiles.id = auth.uid()
            and profiles.role = 'admin'
        )
    );
