package notifications import ( "context" "database/sql" "encoding/json" "errors" "time" "shared-album/internal/models" "shared-album/internal/sqliteutil" ) // SQLiteStore is the SQLite implementation of Repository. type SQLiteStore struct { db *sql.DB } func NewSQLiteStore(db *sql.DB) *SQLiteStore { return &SQLiteStore{db: db} } func (s *SQLiteStore) Create(ctx context.Context, n *models.Notification) error { payload, err := json.Marshal(n.PayloadJSON) if err != nil { return err } var createdAt string err = s.db.QueryRowContext(ctx, `INSERT INTO notifications (id, user_id, type, payload_json) VALUES ($1, $2, $3, $4) RETURNING created_at`, n.ID, n.UserID, n.Type, string(payload)).Scan(&createdAt) if err != nil { return err } n.CreatedAt = sqliteutil.ParseTime(createdAt) return nil } func (s *SQLiteStore) List(ctx context.Context, userID string, limit int) ([]models.Notification, error) { if limit <= 0 || limit > 200 { limit = 100 } rows, err := s.db.QueryContext(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, createdAt string var readAt sql.NullString if err := rows.Scan(&n.ID, &n.UserID, &n.Type, &payload, &readAt, &createdAt); err != nil { return nil, err } _ = json.Unmarshal([]byte(payload), &n.PayloadJSON) n.ReadAt = sqliteutil.ParseNullTime(readAt) n.CreatedAt = sqliteutil.ParseTime(createdAt) out = append(out, n) } return out, rows.Err() } func (s *SQLiteStore) MarkRead(ctx context.Context, id, userID string) error { res, err := s.db.ExecContext(ctx, `UPDATE notifications SET read_at = $3 WHERE id = $1 AND user_id = $2 AND read_at IS NULL`, id, userID, sqliteutil.FormatTime(time.Now())) if err != nil { return err } if n, _ := res.RowsAffected(); n == 0 { var exists int err := s.db.QueryRowContext(ctx, `SELECT 1 FROM notifications WHERE id = $1 AND user_id = $2`, id, userID).Scan(&exists) if err != nil { if errors.Is(err, sql.ErrNoRows) { return ErrNotFound } return err } } return nil }