
-- Create parking_records table for violation tracking
CREATE TABLE public.parking_records (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  association_id UUID NOT NULL REFERENCES public.associations(id),
  title TEXT NOT NULL DEFAULT '',
  description TEXT,
  address TEXT,
  vehicle_plate TEXT,
  vehicle_make TEXT,
  vehicle_model TEXT,
  photo_url TEXT,
  warning_level TEXT NOT NULL DEFAULT 'first_warning' CHECK (warning_level IN ('first_warning', 'second_warning', 'final_warning')),
  recorded_by TEXT,
  recorded_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  citation TEXT,
  status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed', 'resolved')),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

ALTER TABLE public.parking_records ENABLE ROW LEVEL SECURITY;

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

CREATE POLICY "Admin/manager can insert parking records"
  ON public.parking_records FOR INSERT TO authenticated
  WITH CHECK (
    public.has_role(auth.uid(), 'admin') OR public.has_role(auth.uid(), 'manager')
  );

CREATE POLICY "Admin/manager can update parking records"
  ON public.parking_records FOR UPDATE TO authenticated
  USING (
    public.has_role(auth.uid(), 'admin') OR public.has_role(auth.uid(), 'manager')
  );

CREATE POLICY "Admin/manager can delete parking records"
  ON public.parking_records FOR DELETE TO authenticated
  USING (
    public.has_role(auth.uid(), 'admin') OR public.has_role(auth.uid(), 'manager')
  );

CREATE TRIGGER update_parking_records_updated_at
  BEFORE UPDATE ON public.parking_records
  FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();

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

CREATE POLICY "Anyone can view parking photos"
  ON storage.objects FOR SELECT USING (bucket_id = 'parking-photos');

CREATE POLICY "Authenticated can upload parking photos"
  ON storage.objects FOR INSERT TO authenticated
  WITH CHECK (bucket_id = 'parking-photos');

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