package postgres import ( "context" "fmt" "time" "github.com/jackc/pgx/v5/pgxpool" "github.com/charawein/mtusi2026lab2/internal/domain" ) type MessageRepository struct { pool *pgxpool.Pool } func NewMessageRepository(pool *pgxpool.Pool) *MessageRepository { return &MessageRepository{pool: pool} } func (r *MessageRepository) Create(ctx context.Context, msg *domain.Message) error { const q = ` INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5) ` if _, err := r.pool.Exec(ctx, q, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil { return fmt.Errorf("insert message: %w", err) } return nil } func (r *MessageRepository) ListByChat(ctx context.Context, chatID string, cursor time.Time, cursorID string, limit int) ([]*domain.Message, error) { const q = ` SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1::uuid AND (created_at, id) > ($2::timestamptz, $3::uuid) ORDER BY created_at, id LIMIT $4 ` rows, err := r.pool.Query(ctx, q, chatID, cursor, cursorID, limit) if err != nil { return nil, fmt.Errorf("list messages: %w", err) } defer rows.Close() msgs := []*domain.Message{} for rows.Next() { var m domain.Message if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil { return nil, fmt.Errorf("scan message: %w", err) } msgs = append(msgs, &m) } return msgs, rows.Err() }