package user

import (
	"database/sql"
	"studia/internal/logger"
	"time"

	"golang.org/x/crypto/bcrypt"
)

type User struct {
	ID           string    `json:"id"`
	Email        string    `json:"email"`
	Username     string    `json:"username"`
	PasswordHash string    `json:"-"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
	Role         []string  `json:"role"`
}

// type Repository interface {
// 	Create(ctx context.Context, u *User) error
// 	GetByID(ctx context.Context, id int64) (*User, error)
// 	GetByEmail(ctx context.Context, email string) (*User, error)
// 	Update(ctx context.Context, u *User) error
// 	Delete(ctx context.Context, id int64) error
// 	List(ctx context.Context, limit, offset int) ([]*User, error)
// 	CheckPasswordHash(email string, password string) bool
// }

func GetUserByEmail(db *sql.DB, email string) (*User, error) {
	row := db.QueryRow("SELECT id, email, username FROM users WHERE email=$1", email)
	var user User
	err := row.Scan(&user.ID, &user.Email, &user.Username)
	if err != nil {
		return nil, err
	}
	return &user, nil
}

func CheckPasswordHash(db *sql.DB, email string, password string) error {
	row := db.QueryRow("SELECT password_hash FROM users WHERE email=$1", email)
	var hash []byte
	if err := row.Scan(&hash); err != nil {
		return err
	}
	UserPasswordHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	logger.Log.Info().Msgf("UserPasswordHash: %s", UserPasswordHash)
	logger.Log.Info().Msgf("hash: %s", hash)
	logger.Log.Info().Msgf("password: %s", []byte(password))
	logger.Log.Info().Msgf("email: %s", []byte(email))

	err = bcrypt.CompareHashAndPassword(hash, []byte(password))

	return err
}

func CreateUser(db *sql.DB, email string, name string, password string, role []string) error {
	passwordHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}

	_, err = db.Exec("INSERT INTO users (email, username, password_hash) VALUES ($1, $2, $3)",
		email, name, string(passwordHash))
	return err
}
