package repository import ( "context" "errors" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "golang.org/x/crypto/bcrypt" "shop/internal/models" ) type UserRepository struct { pool *pgxpool.Pool } func NewUserRepository(pool *pgxpool.Pool) *UserRepository { return &UserRepository{pool: pool} } func (r *UserRepository) Create(ctx context.Context, email, password, name string) (models.User, error) { hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { return models.User{}, err } var u models.User err = r.pool.QueryRow(ctx, ` INSERT INTO users (email, password_hash, name) VALUES ($1, $2, $3) RETURNING id, email, name, phone, address, created_at `, email, string(hash), name).Scan(&u.ID, &u.Email, &u.Name, &u.Phone, &u.Address, &u.CreatedAt) return u, err } func (r *UserRepository) Authenticate(ctx context.Context, email, password string) (models.User, error) { var hash string var u models.User err := r.pool.QueryRow(ctx, ` SELECT id, email, name, phone, address, created_at, password_hash FROM users WHERE email = $1 `, email).Scan(&u.ID, &u.Email, &u.Name, &u.Phone, &u.Address, &u.CreatedAt, &hash) if errors.Is(err, pgx.ErrNoRows) { return models.User{}, pgx.ErrNoRows } if err != nil { return models.User{}, err } if bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) != nil { return models.User{}, pgx.ErrNoRows } return u, nil } func (r *UserRepository) GetByID(ctx context.Context, id int) (models.User, error) { var u models.User err := r.pool.QueryRow(ctx, ` SELECT id, email, name, phone, address, created_at FROM users WHERE id = $1 `, id).Scan(&u.ID, &u.Email, &u.Name, &u.Phone, &u.Address, &u.CreatedAt) return u, err } func (r *UserRepository) UpdateProfile(ctx context.Context, u *models.User) error { _, err := r.pool.Exec(ctx, ` UPDATE users SET name = $1, phone = $2, address = $3 WHERE id = $4 `, u.Name, u.Phone, u.Address, u.ID) return err } func (r *UserRepository) EmailExists(ctx context.Context, email string) (bool, error) { var exists bool err := r.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM users WHERE email = $1)`, email).Scan(&exists) return exists, err }