-- Fix: only create dashboard + panels for the modules the user selected (enabled_modules).
-- No example checklists, notes, or other seed data.

CREATE OR REPLACE FUNCTION public.create_department_dashboard()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $$
DECLARE
  dash_id uuid;
  i int := 0;
  mod text;
BEGIN
  -- Create the dashboard
  INSERT INTO public.department_dashboards (department_id, created_by)
  VALUES (NEW.id, auth.uid())
  RETURNING id INTO dash_id;

  -- Create a panel for each enabled module
  FOREACH mod IN ARRAY NEW.enabled_modules LOOP
    INSERT INTO public.dashboard_panels (dashboard_id, module, position, width)
    VALUES (dash_id, mod::public.module_type, i, 'half');
    i := i + 1;
  END LOOP;

  RETURN NEW;
END;
$$;
