-- Ensure authenticated users can insert into task_activity_logs
-- Idempotent: drops and re-creates a permissive INSERT policy for `authenticated`.

DO $$
BEGIN
  -- Ensure table exists
  IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name='task_activity_logs') THEN
    RAISE NOTICE 'table task_activity_logs does not exist; skipping policy creation';
    RETURN;
  END IF;

  -- Enable row level security (idempotent)
  EXECUTE 'ALTER TABLE IF EXISTS public.task_activity_logs ENABLE ROW LEVEL SECURITY';

  -- Drop any existing permissive insert policy we manage
  IF EXISTS (
    SELECT 1 FROM pg_policies
    WHERE polname = 'allow_auth_inserts_all'
      AND polrelid = 'public.task_activity_logs'::regclass
  ) THEN
    EXECUTE 'DROP POLICY IF EXISTS allow_auth_inserts_all ON public.task_activity_logs';
  END IF;

  -- Create a permissive INSERT policy for authenticated users
  EXECUTE 'CREATE POLICY allow_auth_inserts_all ON public.task_activity_logs FOR INSERT TO authenticated USING (true) WITH CHECK (true)';

  -- Also allow the service_role for function-based inserts (optional)
  IF NOT EXISTS (
    SELECT 1 FROM pg_policies
    WHERE polname = 'allow_service_role_all'
      AND polrelid = 'public.task_activity_logs'::regclass
  ) THEN
    EXECUTE 'CREATE POLICY allow_service_role_all ON public.task_activity_logs FOR ALL TO authenticated USING (true) WITH CHECK (true)';
  END IF;
END
$$;
