-- Create additional storage buckets for app assets (if not exist)
INSERT INTO storage.buckets (id, name, public)
VALUES 
  ('app-icons', 'app-icons', true),
  ('splash-screens', 'splash-screens', true),
  ('project-assets', 'project-assets', false)
ON CONFLICT (id) DO NOTHING;

-- =====================================================
-- RLS POLICIES FOR APP-ICONS (Public read, owner write)
-- =====================================================

CREATE POLICY "App icons are publicly viewable"
ON storage.objects FOR SELECT
USING (bucket_id = 'app-icons');

CREATE POLICY "Users can upload their own app icons"
ON storage.objects FOR INSERT
WITH CHECK (
  bucket_id = 'app-icons' 
  AND auth.uid()::text = (storage.foldername(name))[1]
);

CREATE POLICY "Users can update their own app icons"
ON storage.objects FOR UPDATE
USING (
  bucket_id = 'app-icons' 
  AND auth.uid()::text = (storage.foldername(name))[1]
);

CREATE POLICY "Users can delete their own app icons"
ON storage.objects FOR DELETE
USING (
  bucket_id = 'app-icons' 
  AND auth.uid()::text = (storage.foldername(name))[1]
);

-- =====================================================
-- RLS POLICIES FOR SPLASH-SCREENS (Public read, owner write)
-- =====================================================

CREATE POLICY "Splash screens are publicly viewable"
ON storage.objects FOR SELECT
USING (bucket_id = 'splash-screens');

CREATE POLICY "Users can upload their own splash screens"
ON storage.objects FOR INSERT
WITH CHECK (
  bucket_id = 'splash-screens' 
  AND auth.uid()::text = (storage.foldername(name))[1]
);

CREATE POLICY "Users can update their own splash screens"
ON storage.objects FOR UPDATE
USING (
  bucket_id = 'splash-screens' 
  AND auth.uid()::text = (storage.foldername(name))[1]
);

CREATE POLICY "Users can delete their own splash screens"
ON storage.objects FOR DELETE
USING (
  bucket_id = 'splash-screens' 
  AND auth.uid()::text = (storage.foldername(name))[1]
);

-- =====================================================
-- RLS POLICIES FOR PROJECT-ASSETS (Private - owner only)
-- =====================================================

CREATE POLICY "Users can view their own project assets"
ON storage.objects FOR SELECT
USING (
  bucket_id = 'project-assets' 
  AND auth.uid()::text = (storage.foldername(name))[1]
);

CREATE POLICY "Users can upload their own project assets"
ON storage.objects FOR INSERT
WITH CHECK (
  bucket_id = 'project-assets' 
  AND auth.uid()::text = (storage.foldername(name))[1]
);

CREATE POLICY "Users can update their own project assets"
ON storage.objects FOR UPDATE
USING (
  bucket_id = 'project-assets' 
  AND auth.uid()::text = (storage.foldername(name))[1]
);

CREATE POLICY "Users can delete their own project assets"
ON storage.objects FOR DELETE
USING (
  bucket_id = 'project-assets' 
  AND auth.uid()::text = (storage.foldername(name))[1]
);