CREATE TABLE IF NOT EXISTS public.activities (
  id                      uuid         PRIMARY KEY DEFAULT gen_random_uuid(),
  process_id              uuid         NOT NULL REFERENCES public.processes(id) ON DELETE CASCADE,
  bpmn_element_id         text         NOT NULL,
  name                    text         NOT NULL DEFAULT '',
  type                    text         NOT NULL DEFAULT 'task' CHECK (type IN ('task','subprocess')),
  direct_cost_fixed       numeric      NOT NULL DEFAULT 0,
  execution_time_minutes  numeric      NOT NULL DEFAULT 0,
  automatable             boolean      NOT NULL DEFAULT false,
  automated_cost_fixed    numeric      NOT NULL DEFAULT 0,
  automated_time_minutes  numeric      NOT NULL DEFAULT 0,
  created_by              uuid         REFERENCES public.users(id),
  updated_by              uuid         REFERENCES public.users(id),
  created_at              timestamptz  NOT NULL DEFAULT now(),
  updated_at              timestamptz  NOT NULL DEFAULT now()
);

CREATE UNIQUE INDEX IF NOT EXISTS activities_process_bpmn_idx
  ON public.activities(process_id, bpmn_element_id);

ALTER TABLE public.activities ENABLE ROW LEVEL SECURITY;

CREATE POLICY "all_activities" ON public.activities
  FOR ALL USING (auth.uid() IS NOT NULL)
  WITH CHECK (auth.uid() IS NOT NULL);
