package repository

import (
	"context"

	sq "github.com/Masterminds/squirrel"

	"git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/helper/errors"
	"git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/model"
)

const (
	userTableName = "user"
)

type UserRepository struct {
	db DB
}

func InitUserRepository(db DB) *UserRepository {
	return &UserRepository{db: db}
}

func (u UserRepository) Get(
	ctx context.Context,
	username string,
) (*model.User, error) {
	var res model.User

	q, v, err := sq.Select("id", "username", "password", "created_at", "updated_at").
		From(userTableName).
		PlaceholderFormat(placeholder).
		Where(sq.Eq{"username": username}).
		ToSql()

	if err != nil {
		return nil, errors.Wrap(err, "build query")
	}

	err = u.db.GetContext(ctx, &res, q, v...)
	if err != nil {
		return nil, errors.Wrap(err, "get")
	}

	return &res, nil
}

func (u UserRepository) Add(
	ctx context.Context,
	username string,
	password string,
) (uint64, error) {
	q, v, err := sq.Insert(userTableName).
		PlaceholderFormat(placeholder).
		Columns("username", "password").
		Values(username, password).
		ToSql()

	if err != nil {
		return 0, errors.Wrap(err, "build query")
	}

	res, err := u.db.ExecContext(ctx, q, v...)
	if err != nil {
		return 0, errors.Wrap(err, "exec")
	}

	id, err := res.LastInsertId()
	if err != nil {
		return 0, errors.Wrap(err, "can't get last insert id")
	}

	return uint64(id), nil
}

func (u UserRepository) UpdatePassword(
	ctx context.Context,
	id uint64,
	newPassword string,
) error {
	q, v, err := sq.Update(userTableName).
		PlaceholderFormat(placeholder).
		Set("password", newPassword).
		Where(sq.Eq{"id": id}).
		ToSql()

	if err != nil {
		return errors.Wrap(err, "build query")
	}

	_, err = u.db.ExecContext(ctx, q, v...)
	if err != nil {
		return errors.Wrap(err, "exec")
	}

	return nil
}
