package postgres import ( "context" "encoding/json" "fmt" "strings" "time" "datarush/internal/competition/repository" pb "datarush/pkg/api/competition" "github.com/google/uuid" "github.com/jmoiron/sqlx" "github.com/redis/go-redis/v9" ) const ( competitionCachePrefix = "competition:" ) type CompetitionRepository struct { db *sqlx.DB redisClient *redis.Client cacheEnabled bool } func NewCompetitionRepository( db *sqlx.DB, redisClient *redis.Client, cacheEnabled bool, ) repository.CompetitionRepository { return &CompetitionRepository{ db: db, redisClient: redisClient, cacheEnabled: cacheEnabled, } } func (r *CompetitionRepository) cacheKey(id string) string { return competitionCachePrefix + id } func (r *CompetitionRepository) Create(ctx context.Context, c *pb.Competition) (*pb.Competition, error) { query := `INSERT INTO competitions (state, title, description, image_url, start_time, end_time, type, participation_type) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id, created_at, updated_at` var createdCompetition pb.Competition err := r.db.QueryRowxContext(ctx, query, c.State, c.Title, c.Description, c.ImageUrl, c.StartTime.AsTime(), c.EndTime.AsTime(), c.Type, c.ParticipationType, ).StructScan(&createdCompetition) if err != nil { return nil, err } c.Id = createdCompetition.Id c.CreatedAt = createdCompetition.CreatedAt c.UpdatedAt = createdCompetition.UpdatedAt if r.cacheEnabled { data, err := json.Marshal(c) if err == nil { r.redisClient.Set(ctx, r.cacheKey(c.Id), data, 10*time.Minute).Err() } } return c, nil } func (r *CompetitionRepository) Get(ctx context.Context, id uuid.UUID) (*pb.Competition, error) { if r.cacheEnabled { val, err := r.redisClient.Get(ctx, r.cacheKey(id.String())).Result() if err == nil { var competition pb.Competition if json.Unmarshal([]byte(val), &competition) == nil { return &competition, nil } } } query := `SELECT id, state, title, description, image_url, start_time, end_time, type, participation_type, created_at, updated_at FROM competitions WHERE id = $1` var competition pb.Competition err := r.db.GetContext(ctx, &competition, query, id) if err != nil { return nil, err } if r.cacheEnabled { data, err := json.Marshal(&competition) if err == nil { r.redisClient.Set(ctx, r.cacheKey(id.String()), data, 10*time.Minute).Err() } } return &competition, nil } func (r *CompetitionRepository) Update(ctx context.Context, c *pb.Competition) (*pb.Competition, error) { query := `UPDATE competitions SET state = $2, title = $3, description = $4, image_url = $5, start_time = $6, end_time = $7, type = $8, participation_type = $9, updated_at = now() WHERE id = $1 RETURNING updated_at` var updatedCompetition pb.Competition err := r.db.QueryRowxContext(ctx, query, c.Id, c.State, c.Title, c.Description, c.ImageUrl, c.StartTime.AsTime(), c.EndTime.AsTime(), c.Type, c.ParticipationType, ).StructScan(&updatedCompetition) if err != nil { return nil, err } c.UpdatedAt = updatedCompetition.UpdatedAt if r.cacheEnabled { r.redisClient.Del(ctx, r.cacheKey(c.Id)).Err() } return c, nil } func (r *CompetitionRepository) Delete(ctx context.Context, id uuid.UUID) error { query := `DELETE FROM competitions WHERE id = $1` _, err := r.db.ExecContext(ctx, query, id) if err != nil { return err } if r.cacheEnabled { r.redisClient.Del(ctx, r.cacheKey(id.String())).Err() } return nil } func (r *CompetitionRepository) List( ctx context.Context, opts repository.ListCompetitionsOptions, ) ([]*pb.Competition, int, error) { var args []interface{} var whereClauses []string argId := 1 if opts.State != nil { whereClauses = append(whereClauses, fmt.Sprintf("state = $%d", argId)) args = append(args, *opts.State) argId++ } if opts.SearchQuery != nil { whereClauses = append(whereClauses, fmt.Sprintf("title ILIKE $%d", argId)) args = append(args, "%"+*opts.SearchQuery+"%") argId++ } if opts.IsParticipating != nil { userID, ok := ctx.Value("user_id").(string) if !ok { return nil, 0, fmt.Errorf("user not authenticated or user_id not in context") } if *opts.IsParticipating { whereClauses = append( whereClauses, fmt.Sprintf("id IN (SELECT competition_id FROM user_competitions WHERE user_id = $%d)", argId), ) } else { whereClauses = append(whereClauses, fmt.Sprintf("id NOT IN (SELECT competition_id FROM user_competitions WHERE user_id = $%d)", argId)) } args = append(args, userID) argId++ } where := "" if len(whereClauses) > 0 { where = "WHERE " + strings.Join(whereClauses, " AND ") } countQuery := "SELECT COUNT(*) FROM competitions " + where var total int if err := r.db.GetContext(ctx, &total, countQuery, args...); err != nil { return nil, 0, err } query := fmt.Sprintf( `SELECT id, state, title, description, image_url, start_time, end_time, type, participation_type, created_at, updated_at FROM competitions %s ORDER BY created_at DESC LIMIT $%d OFFSET $%d`, where, argId, argId+1, ) args = append(args, opts.PageSize, (opts.Page-1)*opts.PageSize) var competitions []*pb.Competition err := r.db.SelectContext(ctx, &competitions, query, args...) if err != nil { return nil, 0, err } return competitions, total, nil } func (r *CompetitionRepository) ChangeState( ctx context.Context, id uuid.UUID, state pb.CompetitionState, ) (*pb.Competition, error) { query := `UPDATE competitions SET state = $1, updated_at = $2 WHERE id = $3 RETURNING updated_at` now := time.Now() var competition pb.Competition err := r.db.QueryRowxContext(ctx, query, state, now, id).StructScan(&competition) if err != nil { return nil, err } if r.cacheEnabled { r.redisClient.Del(ctx, r.cacheKey(id.String())).Err() } return r.Get(ctx, id) }