package repositories

import (
	"context"
	"database/sql"

	"gitea.d3m0k1d.ru/d3m0k1d/d3m0k1d.ru/backend/internal/logger"
	"gitea.d3m0k1d.ru/d3m0k1d/d3m0k1d.ru/backend/internal/storage"
)

type authRepository struct {
	db     *sql.DB
	logger *logger.Logger
}

func NewAuthRepository(db *sql.DB) AuthRepository {
	return &authRepository{
		db:     db,
		logger: logger.New(false),
	}
}

func (a *authRepository) Register(ctx context.Context, user storage.UserReg) (int, error) {
	var id int
	_, err := a.db.ExecContext(ctx,
		"INSERT INTO users(email, github_id, github_login, avatar_url) VALUES(?, ?, ?, ?)",
		user.Email, user.GithubID, user.GithubLogin, user.AvatarURL,
	)
	if err != nil {
		a.logger.Error("error insert: " + err.Error())
		return 0, err
	}

	row := a.db.QueryRowContext(ctx, "SELECT id FROM users WHERE github_id = ?", user.GithubID)
	err = row.Scan(&id)
	if err != nil {
		a.logger.Error("error scan: " + err.Error())
		return 0, err
	}

	a.logger.Info("User registered: " + user.Email)
	return id, nil
}

func (a *authRepository) IsRegistered(ctx context.Context, github_id int) (bool, error) {
	var id int
	err := a.db.QueryRowContext(ctx, "SELECT id FROM users WHERE github_id = ?", github_id).
		Scan(&id)
	if err != nil {
		if err == sql.ErrNoRows {
			return false, nil
		}
		return false, err
	}
	return true, nil
}

func (r *authRepository) GetUserByGithubID(
	ctx context.Context,
	githubID int,
) (*storage.User, error) {
	var user storage.User
	query := `SELECT id, github_id, github_login, email, avatar_url FROM users WHERE github_id = ?`

	err := r.db.QueryRowContext(ctx, query, githubID).Scan(
		&user.ID,
		&user.GithubID,
		&user.GithubLogin,
		&user.Email,
		&user.AvatarURL,
	)
	if err != nil {
		return nil, err
	}

	return &user, nil
}
