-- inboxes

INSERT INTO inboxes (
  user_id,
  total_open_threads,
  total_unread_messages,
  created_at,
  updated_at
) SELECT
    user_id,
    total_open_threads,
    0,
    created_at,
    changed_at
  FROM chat_user_inboxes;

-- inbox_threads

SET IDENTITY_INSERT inbox_threads ON;
INSERT INTO inbox_threads (
  id,
  user_id,
  ticket_id,
  "left",
  archived,
  total_unread,
  created_at,
  updated_at,
  sorted_at
) SELECT
    id,
    user_id,
    ticket_id,
    deleted,
    deleted,
    0,
    created_at,
    created_at,
    created_at
  FROM ticket_members;
SET IDENTITY_INSERT inbox_threads OFF;

-- inbox_threads message_id

UPDATE inbox_threads
SET
  message_id = (
    SELECT max(ticket_messages.id)
    FROM ticket_messages
    WHERE ticket_messages.ticket_id = inbox_threads.ticket_id
  );

-- Inbox thread updated_at

UPDATE inbox_threads
SET
  sorted_at = (
    SELECT m.created_at
    FROM ticket_messages m
    WHERE m.id = inbox_threads.message_id
  )
WHERE message_id IS NOT NULL;
