
-- Add logo_url to associations table
ALTER TABLE public.associations ADD COLUMN IF NOT EXISTS logo_url text;

-- Create company_settings table for company-level branding
CREATE TABLE IF NOT EXISTS public.company_settings (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  key text NOT NULL UNIQUE,
  value text,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
);

ALTER TABLE public.company_settings ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Staff full access on company_settings"
  ON public.company_settings
  FOR ALL
  TO authenticated
  USING (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager'))
  WITH CHECK (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager'));

CREATE POLICY "Authenticated users can view company_settings"
  ON public.company_settings
  FOR SELECT
  TO authenticated
  USING (true);

-- Create public logos storage bucket
INSERT INTO storage.buckets (id, name, public)
VALUES ('logos', 'logos', true)
ON CONFLICT (id) DO NOTHING;

-- Allow authenticated users to upload to logos bucket
CREATE POLICY "Authenticated users can upload logos"
  ON storage.objects
  FOR INSERT
  TO authenticated
  WITH CHECK (bucket_id = 'logos');

-- Allow public read access to logos
CREATE POLICY "Public read access to logos"
  ON storage.objects
  FOR SELECT
  TO public
  USING (bucket_id = 'logos');

-- Allow authenticated users to update/delete logos
CREATE POLICY "Authenticated users can manage logos"
  ON storage.objects
  FOR DELETE
  TO authenticated
  USING (bucket_id = 'logos');

CREATE POLICY "Authenticated users can update logos"
  ON storage.objects
  FOR UPDATE
  TO authenticated
  USING (bucket_id = 'logos');
