package postgres import ( "context" "database/sql" "datarush/internal/competition/domain" "datarush/internal/competition/repository" "encoding/json" "fmt" "strings" "time" "github.com/google/uuid" "github.com/redis/go-redis/v9" ) const ( competitionCachePrefix = "competition:" ) type CompetitionRepository struct { db *sql.DB redisClient *redis.Client cacheEnabled bool } func NewCompetitionRepository(db *sql.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, competition *domain.Competition) error { query := `INSERT INTO competitions (id, state, title, description, image_url, start_time, end_time, type, participation_type, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)` _, err := r.db.ExecContext(ctx, query, competition.ID, competition.State, competition.Title, competition.Description, competition.ImageURL, competition.StartTime, competition.EndTime, competition.Type, competition.ParticipationType, competition.CreatedAt, competition.UpdatedAt, ) if err != nil { return err } if r.cacheEnabled { data, err := json.Marshal(competition) if err == nil { r.redisClient.Set(ctx, r.cacheKey(competition.ID.String()), data, 10*time.Minute).Err() } } return nil } func (r *CompetitionRepository) Get(ctx context.Context, id uuid.UUID) (*domain.Competition, error) { if r.cacheEnabled { val, err := r.redisClient.Get(ctx, r.cacheKey(id.String())).Result() if err == nil { var competition domain.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` row := r.db.QueryRowContext(ctx, query, id) var competition domain.Competition err := row.Scan( &competition.ID, &competition.State, &competition.Title, &competition.Description, &competition.ImageURL, &competition.StartTime, &competition.EndTime, &competition.Type, &competition.ParticipationType, &competition.CreatedAt, &competition.UpdatedAt, ) 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, competition *domain.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 = $10 WHERE id = $1` _, err := r.db.ExecContext(ctx, query, competition.ID, competition.State, competition.Title, competition.Description, competition.ImageURL, competition.StartTime, competition.EndTime, competition.Type, competition.ParticipationType, competition.UpdatedAt, ) if err != nil { return err } if r.cacheEnabled { r.redisClient.Del(ctx, r.cacheKey(competition.ID.String())).Err() } return 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) ([]domain.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").(uuid.UUID) 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 competition_participants WHERE user_id = $%d)", argId)) } else { whereClauses = append(whereClauses, fmt.Sprintf("id NOT IN (SELECT competition_id FROM competition_participants 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.QueryRowContext(ctx, countQuery, args...).Scan(&total); 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*opts.PageSize) rows, err := r.db.QueryContext(ctx, query, args...) if err != nil { return nil, 0, err } defer rows.Close() var competitions []domain.Competition for rows.Next() { var c domain.Competition err := rows.Scan( &c.ID, &c.State, &c.Title, &c.Description, &c.ImageURL, &c.StartTime, &c.EndTime, &c.Type, &c.ParticipationType, &c.CreatedAt, &c.UpdatedAt, ) if err != nil { return nil, 0, err } competitions = append(competitions, c) } return competitions, total, nil } func (r *CompetitionRepository) ChangeState(ctx context.Context, id uuid.UUID, state domain.CompetitionState) (*domain.Competition, error) { query := `UPDATE competitions SET state = $1, updated_at = $2 WHERE id = $3` now := time.Now() _, err := r.db.ExecContext(ctx, query, state, now, id) if err != nil { return nil, err } if r.cacheEnabled { r.redisClient.Del(ctx, r.cacheKey(id.String())).Err() } return r.Get(ctx, id) }