package notifications import ( "context" "encoding/json" "errors" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "shared-album/internal/models" ) var ErrNotFound = errors.New("not found") type Store struct { pool *pgxpool.Pool } func NewStore(pool *pgxpool.Pool) *Store { return &Store{pool: pool} } func (s *Store) Create(ctx context.Context, n *models.Notification) error { payload, err := json.Marshal(n.PayloadJSON) if err != nil { return err } return s.pool.QueryRow(ctx, `INSERT INTO notifications (id, user_id, type, payload_json) VALUES ($1, $2, $3, $4) RETURNING created_at`, n.ID, n.UserID, n.Type, payload, ).Scan(&n.CreatedAt) } func (s *Store) List(ctx context.Context, userID string, limit int) ([]models.Notification, error) { if limit <= 0 || limit > 200 { limit = 100 } rows, err := s.pool.Query(ctx, `SELECT id, user_id, type, payload_json, read_at, created_at FROM notifications WHERE user_id = $1 ORDER BY created_at DESC LIMIT $2`, userID, limit) if err != nil { return nil, err } defer rows.Close() out := []models.Notification{} for rows.Next() { var n models.Notification var payload []byte if err := rows.Scan(&n.ID, &n.UserID, &n.Type, &payload, &n.ReadAt, &n.CreatedAt); err != nil { return nil, err } _ = json.Unmarshal(payload, &n.PayloadJSON) out = append(out, n) } return out, rows.Err() } func (s *Store) MarkRead(ctx context.Context, id, userID string) error { tag, err := s.pool.Exec(ctx, `UPDATE notifications SET read_at = now() WHERE id = $1 AND user_id = $2 AND read_at IS NULL`, id, userID) if err != nil { return err } if tag.RowsAffected() == 0 { var exists bool if err := s.pool.QueryRow(ctx, `SELECT true FROM notifications WHERE id = $1 AND user_id = $2`, id, userID).Scan(&exists); err != nil { if errors.Is(err, pgx.ErrNoRows) { return ErrNotFound } return err } } return nil }