-- Conversations messages table
alter table comunic_conversations_messages rename column time_insert to time_sent;
alter table comunic_conversations_messages modify message TEXT;
alter table comunic_conversations_messages
	add column filepath varchar(255) default null,
    add column file_size int default null,
    add column file_name varchar(255) default null,
    add column file_thumbnail varchar(255) default null,
    add column file_type varchar(128) default null;
update comunic_conversations_messages set filepath = image_path, file_size = 10, file_type = "image/png", file_name = "image.png" where image_path is not null and id >= 1;
alter table comunic_conversations_messages drop column image_path;

-- Conversations members table
ALTER TABLE `comunic_conversations_users` RENAME TO  `comunic_conversations_members` ;
ALTER TABLE comunic_conversations_members rename column time_add to added_on;
alter table comunic_conversations_members drop column saw_last_message;
alter table comunic_conversations_members
	add column is_admin int default 1,
    add column last_message_seen int default 0;

-- Conversations list table
alter table comunic_conversations_list drop column user_id;
alter table comunic_conversations_list drop column last_active;
alter table comunic_conversations_list
	add column color varchar(6),
    add column background varchar(255),
    add group_id int;

-- Conversations view
CREATE VIEW comunic_conversations_info AS
    SELECT
        l.id,
        m.user_id,
        l.name,
        l.color,
        l.background,
        l.creation_time,
        l.group_id,
        l.can_everyone_add_members,
        m.is_admin,
        m.added_on AS user_added_on,
        m.following,
        m.last_message_seen,
        msg.id AS last_msg_id,
        msg.time_sent AS last_msg_time_sent,
        msg.user_id AS last_msg_user_id,
        msg.message AS last_msg_message,
        msg.filepath AS last_msg_filepath,
        msg.file_size AS last_msg_file_size,
        msg.file_name AS last_msg_file_name,
        msg.file_thumbnail AS last_msg_file_thumbnail,
        msg.file_type AS last_msg_file_type
    FROM
        comunic_conversations_list l
            JOIN
        comunic_conversations_members m ON l.id = m.conv_id
            JOIN
        (SELECT
            MAX(id) AS max_msg_id, conv_id
        FROM
            comunic_conversations_messages
        GROUP BY conv_id) msg_id ON msg_id.conv_id = l.id
            JOIN
        comunic_conversations_messages msg ON msg.id = msg_id.max_msg_id;