89 lines
2.4 KiB
Go
89 lines
2.4 KiB
Go
package database
|
|
|
|
import (
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"github.com/google/uuid"
|
|
"log"
|
|
)
|
|
|
|
func DeleteContact(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (string, error) {
|
|
// Check conversation type
|
|
var conversationType string
|
|
err := db.QueryRow(
|
|
"SELECT conversation_type FROM Conversations WHERE conversation_id = $1",
|
|
conversationID,
|
|
).Scan(&conversationType)
|
|
if err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return "no conversation found for this id", nil
|
|
}
|
|
return "", fmt.Errorf("error checking conversation type: %w", err)
|
|
}
|
|
|
|
if conversationType == "group" {
|
|
// Delete from Contacts
|
|
res, err := db.Exec(
|
|
"DELETE FROM Contacts WHERE conversation_id = $1 AND user_id = $2",
|
|
conversationID,
|
|
userID,
|
|
)
|
|
if err != nil {
|
|
return "", fmt.Errorf("error deleting contact: %w", err)
|
|
}
|
|
|
|
rowsAffected, err := res.RowsAffected()
|
|
if err != nil {
|
|
return "", fmt.Errorf("error checking contact deletion: %w", err)
|
|
}
|
|
if rowsAffected == 0 {
|
|
return fmt.Sprintf("no matching contact found with conversation id: %s, user id: %s", conversationID, userID), nil
|
|
}
|
|
|
|
// Delete from Memberships
|
|
res, err = db.Exec(
|
|
"DELETE FROM Memberships WHERE conversation_id = $1 AND user_id = $2",
|
|
conversationID,
|
|
userID,
|
|
)
|
|
if err != nil {
|
|
return "", fmt.Errorf("error deleting membership: %w", err)
|
|
}
|
|
|
|
rowsAffected, err = res.RowsAffected()
|
|
if err != nil {
|
|
return "", fmt.Errorf("error checking membership deletion: %w", err)
|
|
}
|
|
if rowsAffected == 0 {
|
|
return "", fmt.Errorf("no matching membership found with conversation id: %s, user id: %s", conversationID, userID)
|
|
}
|
|
|
|
log.Printf("Successfully removed user %s from group %s", userID, conversationID)
|
|
} else {
|
|
// Handle direct conversation
|
|
res, err := db.Exec(
|
|
"DELETE FROM Contacts WHERE user_id = $1 AND conversation_id = $2",
|
|
userID,
|
|
conversationID,
|
|
)
|
|
if err != nil {
|
|
log.Printf("Error deleting contact: %v", err)
|
|
return "", fmt.Errorf("error deleting contact: %w", err)
|
|
}
|
|
|
|
rowsAffected, err := res.RowsAffected()
|
|
if err != nil {
|
|
log.Printf("Error checking contact deletion: %v", err)
|
|
return "", fmt.Errorf("error checking contact deletion: %w", err)
|
|
}
|
|
if rowsAffected == 0 {
|
|
return fmt.Sprintf("no matching contact found with user id: %s, conversation id: %s", userID, conversationID), nil
|
|
}
|
|
|
|
log.Printf("Successfully deleted contact for user %s in conversation %s", userID, conversationID)
|
|
}
|
|
|
|
return "", nil
|
|
}
|