package user

import (
	"database/sql"
	"time"

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

type User struct {
	ID           string    `json:"id"`
	Email        string    `json:"email"`
	Name         string    `json:"name"`
	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, password_hash, role FROM users WHERE email=$1", email)
	var user User
	err := row.Scan(&user.ID, &user.Email, &user.PasswordHash, &user.Role)
	if err != nil {
		return nil, err
	}
	return &user, nil
}

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

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, name, password_hash, role, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6)",
		email, name, string(passwordHash), role, time.Now(), time.Now())
	return err
}
