CREATE TABLE chats (
                       id SERIAL PRIMARY KEY,
                       user1_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
                       user2_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
                       created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
                       updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
                       UNIQUE(user1_id, user2_id),  -- Уникальный чат между двумя пользователями
                       CHECK (user1_id < user2_id)  -- Предотвращение дублирования чатов (1-2 и 2-1)
);
-- Сообщения
CREATE TABLE messages (
                          id SERIAL PRIMARY KEY,
                          chat_id INTEGER NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
                          sender_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
                          receiver_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
                          content TEXT NOT NULL,
                          status VARCHAR(20) NOT NULL DEFAULT 'sent' CHECK (status IN ('sent', 'delivered', 'read')),
                          created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
-- Индексы для производительности
CREATE INDEX idx_messages_chat_id ON messages(chat_id);
CREATE INDEX idx_messages_sender_id ON messages(sender_id);
CREATE INDEX idx_chats_user1_id ON chats(user1_id);
CREATE INDEX idx_chats_user2_id ON chats(user2_id);