-- Per-field positioning, fonts, labels, and logo support for check layouts
ALTER TABLE public.check_layouts
  ADD COLUMN IF NOT EXISTS field_positions jsonb NOT NULL DEFAULT '{}'::jsonb,
  ADD COLUMN IF NOT EXISTS logo_url text,
  ADD COLUMN IF NOT EXISTS font_family text NOT NULL DEFAULT 'helvetica',
  ADD COLUMN IF NOT EXISTS show_field_labels boolean NOT NULL DEFAULT false;

-- Storage policies for check logos (reuse the public check-signatures bucket)
INSERT INTO storage.buckets (id, name, public)
VALUES ('check-logos', 'check-logos', true)
ON CONFLICT (id) DO NOTHING;

DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname = 'storage' AND tablename = 'objects' AND policyname = 'Public read check logos') THEN
    CREATE POLICY "Public read check logos" ON storage.objects FOR SELECT USING (bucket_id = 'check-logos');
  END IF;
  IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname = 'storage' AND tablename = 'objects' AND policyname = 'Staff write check logos') THEN
    CREATE POLICY "Staff write check logos" ON storage.objects FOR INSERT TO authenticated WITH CHECK (
      bucket_id = 'check-logos' AND (
        public.has_role(auth.uid(), 'admin'::public.app_role)
        OR public.has_role(auth.uid(), 'manager'::public.app_role)
      )
    );
  END IF;
  IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname = 'storage' AND tablename = 'objects' AND policyname = 'Staff update check logos') THEN
    CREATE POLICY "Staff update check logos" ON storage.objects FOR UPDATE TO authenticated USING (
      bucket_id = 'check-logos' AND (
        public.has_role(auth.uid(), 'admin'::public.app_role)
        OR public.has_role(auth.uid(), 'manager'::public.app_role)
      )
    );
  END IF;
  IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname = 'storage' AND tablename = 'objects' AND policyname = 'Staff delete check logos') THEN
    CREATE POLICY "Staff delete check logos" ON storage.objects FOR DELETE TO authenticated USING (
      bucket_id = 'check-logos' AND (
        public.has_role(auth.uid(), 'admin'::public.app_role)
        OR public.has_role(auth.uid(), 'manager'::public.app_role)
      )
    );
  END IF;
END
$$;