-- Fix: width must be 'full'|'half'|'third'|'two_thirds', not '1'

CREATE OR REPLACE FUNCTION public.create_department_dashboard()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $$
DECLARE
  dash_id uuid;
  checklist_id uuid;
  note_id uuid;
  current_user_id uuid := auth.uid();
BEGIN
  INSERT INTO public.department_dashboards (department_id, created_by)
  VALUES (NEW.id, current_user_id)
  RETURNING id INTO dash_id;

  INSERT INTO public.dashboard_panels (dashboard_id, module, position, width)
  VALUES
    (dash_id, 'kanban', 0, 'half'),
    (dash_id, 'files', 1, 'half'),
    (dash_id, 'checklist', 2, 'half'),
    (dash_id, 'notes', 3, 'half');

  INSERT INTO public.department_checklists (department_id, title, created_by)
  VALUES (NEW.id, 'Getting Started', current_user_id)
  RETURNING id INTO checklist_id;

  INSERT INTO public.department_checklist_items (checklist_id, title, position)
  VALUES
    (checklist_id, 'Set up department goals', 0),
    (checklist_id, 'Assign team members', 1),
    (checklist_id, 'Create initial tasks', 2);

  INSERT INTO public.department_notes (department_id, title, content, created_by)
  VALUES (NEW.id, 'Welcome', 'Welcome to your department! Use this space for notes and documentation.', current_user_id);

  RETURN NEW;
END;
$$;
