package main

import (
	"context"
	"errors"

	"golang.org/x/crypto/bcrypt"

	"github.com/jackc/pgx/v5"
)

var dbConnection *pgx.Conn

func InitDatabase(ctx context.Context) {
	conn, err := pgx.Connect(ctx, "postgres://master:secret@localhost:5432")
	if err != nil {
		panic(err)
	}

	_, err = conn.Exec(ctx, `
		CREATE TABLE IF NOT EXISTS users (
		    Id SERIAL PRIMARY KEY,
		    Name VARCHAR(20) UNIQUE NOT NULL,
		    pass_hash VARCHAR(60) NOT NULL,
		    Color VARCHAR(3) NOT NULL
		)
	`)
	if err != nil {
		panic(err)
	}
	dbConnection = conn
}

func AddNewUser(ctx context.Context, user User) (uint, error) {
	var id uint
	var err error

	if len(user.Name) == 0 || len(user.Name) > 20 {
		return 0, errors.New("username bad length")
	}
	if user.IsPasswordHashed {
		if len(user.Password) != 60 {
			return 0, errors.New("password bad length")
		}
	} else {
		var hashed []byte
		hashed, err = bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
		if err != nil {
			return 0, err
		}
		user.Password = string(hashed)
	}
	if len(user.Color) != 1 && len(user.Color) != 3 {
		return 0, errors.New("color invalid")
	}
	err = dbConnection.QueryRow(ctx, `
        INSERT INTO users (Name, pass_hash, Color)
        VALUES ($1, $2, $3)
        RETURNING Id
    `, user.Name, user.IsPasswordHashed, user.Color).Scan(&id)
	return id, err
}

func CheckPassword(ctx context.Context, id string, plainPassword string) bool {
	var controlHash string
	err := dbConnection.QueryRow(ctx, "SELECT pass_hash FROM users WHERE Id = $1", id).Scan(&controlHash)
	if err != nil {
		return false
	}

	return bcrypt.CompareHashAndPassword([]byte(controlHash), []byte(plainPassword)) == nil
}

func GetUserData(ctx context.Context, id string) (User, error) {
	var user User
	err := dbConnection.QueryRow(ctx, "SELECT Id, Name, pass_hash, Color FROM users WHERE Id = $1", id).
		Scan(&user.Id, &user.Name, &user.Password, &user.Color)
	if err != nil {
		return User{}, err
	}
	user.IsPasswordHashed = true
	return user, nil
}
