CREATE OR REPLACE FUNCTION next_case_number(p_now TIMESTAMPTZ DEFAULT NOW())
RETURNS VARCHAR(50)
LANGUAGE plpgsql
AS $$
DECLARE
  v_period_key VARCHAR(7);
  v_next_value INTEGER;
BEGIN
  v_period_key := TO_CHAR(p_now, 'YYYY_MM');

  INSERT INTO case_number_counter (period_key, last_value, updated_at)
  VALUES (v_period_key, 1, NOW())
  ON CONFLICT (period_key)
  DO UPDATE SET
    last_value = case_number_counter.last_value + 1,
    updated_at = NOW()
  RETURNING case_number_counter.last_value INTO v_next_value;

  RETURN v_period_key || '_' || LPAD(v_next_value::TEXT, 4, '0');
END;
$$;

ALTER TABLE meeting_agenda_item
  ALTER COLUMN meeting_id DROP NOT NULL;

ALTER TABLE meeting_agenda_item
  ALTER COLUMN agenda_number DROP NOT NULL;

CREATE INDEX IF NOT EXISTS idx_meeting_agenda_item_meeting_id ON meeting_agenda_item(meeting_id);
CREATE INDEX IF NOT EXISTS idx_meeting_agenda_item_unassigned ON meeting_agenda_item(id) WHERE meeting_id IS NULL;
