ALTER TABLE meeting_agenda_item
  ADD COLUMN IF NOT EXISTS status VARCHAR(30) NOT NULL DEFAULT 'offen';

ALTER TABLE meeting_agenda_item
  ADD COLUMN IF NOT EXISTS returned_from_meeting_id BIGINT REFERENCES meeting(id) ON DELETE SET NULL;

ALTER TABLE meeting_agenda_item
  ADD COLUMN IF NOT EXISTS returned_at TIMESTAMPTZ;

ALTER TABLE meeting_agenda_item
  ADD COLUMN IF NOT EXISTS returned_by BIGINT REFERENCES app_user(id) ON DELETE SET NULL;

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1
      FROM pg_constraint
     WHERE conname = 'chk_meeting_agenda_item_status'
       AND conrelid = 'meeting_agenda_item'::regclass
  ) THEN
    ALTER TABLE meeting_agenda_item
      ADD CONSTRAINT chk_meeting_agenda_item_status
      CHECK (status IN ('offen', 'in_sitzung', 'rueckfrage', 'klaerung', 'erledigt'));
  END IF;
END $$;

UPDATE meeting_agenda_item
   SET status = CASE WHEN meeting_id IS NULL THEN 'offen' ELSE 'in_sitzung' END
 WHERE status IS NULL
    OR status NOT IN ('offen', 'in_sitzung', 'rueckfrage', 'klaerung', 'erledigt')
    OR (meeting_id IS NOT NULL AND status = 'offen');

CREATE TABLE IF NOT EXISTS meeting_agenda_item_return_log (
  id BIGSERIAL PRIMARY KEY,
  agenda_item_id BIGINT NOT NULL REFERENCES meeting_agenda_item(id) ON DELETE CASCADE,
  meeting_id BIGINT NOT NULL REFERENCES meeting(id) ON DELETE CASCADE,
  agenda_number_at_return VARCHAR(20),
  title_at_return VARCHAR(255) NOT NULL,
  return_type VARCHAR(30) NOT NULL DEFAULT 'rueckfrage',
  remark TEXT NOT NULL,
  include_in_protocol BOOLEAN NOT NULL DEFAULT TRUE,
  returned_by BIGINT REFERENCES app_user(id) ON DELETE SET NULL,
  returned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  CONSTRAINT chk_meeting_agenda_item_return_type CHECK (return_type IN ('rueckfrage', 'klaerung', 'bemerkung'))
);

CREATE INDEX IF NOT EXISTS idx_meeting_agenda_item_status ON meeting_agenda_item(status);
CREATE INDEX IF NOT EXISTS idx_meeting_agenda_item_return_log_meeting ON meeting_agenda_item_return_log(meeting_id, returned_at DESC);
CREATE INDEX IF NOT EXISTS idx_meeting_agenda_item_return_log_agenda ON meeting_agenda_item_return_log(agenda_item_id, returned_at DESC);
