
-- Add new columns to owner_updates table
ALTER TABLE public.owner_updates 
  ADD COLUMN IF NOT EXISTS unit_id uuid REFERENCES public.units(id),
  ADD COLUMN IF NOT EXISTS posted_at timestamptz DEFAULT now(),
  ADD COLUMN IF NOT EXISTS attachments jsonb DEFAULT '[]'::jsonb,
  ADD COLUMN IF NOT EXISTS collection_ids jsonb DEFAULT '[]'::jsonb,
  ADD COLUMN IF NOT EXISTS violation_ids jsonb DEFAULT '[]'::jsonb,
  ADD COLUMN IF NOT EXISTS tags jsonb DEFAULT '[]'::jsonb;

-- Create owner_update_tags table
CREATE TABLE IF NOT EXISTS public.owner_update_tags (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  name text NOT NULL,
  color text NOT NULL DEFAULT 'blue',
  association_id uuid REFERENCES public.associations(id) ON DELETE CASCADE NOT NULL,
  created_at timestamptz DEFAULT now(),
  UNIQUE(name, association_id)
);

ALTER TABLE public.owner_update_tags ENABLE ROW LEVEL SECURITY;

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

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

-- Storage policies for owner update attachments
CREATE POLICY "Authenticated users can upload owner update attachments"
  ON storage.objects FOR INSERT TO authenticated
  WITH CHECK (bucket_id = 'owner-update-attachments');

CREATE POLICY "Anyone can view owner update attachments"
  ON storage.objects FOR SELECT TO authenticated
  USING (bucket_id = 'owner-update-attachments');

CREATE POLICY "Staff can delete owner update attachments"
  ON storage.objects FOR DELETE TO authenticated
  USING (bucket_id = 'owner-update-attachments' AND (
    (SELECT has_role(auth.uid(), 'admin'::app_role)) OR 
    (SELECT has_role(auth.uid(), 'manager'::app_role))
  ));
