package services

import (
	"authentication/db"
	"log"
)

func GetUser(email string) (string, *string, *string, string, error) {
	log.Print(email)
	query := `SELECT id, first_name, last_name, email_address FROM users WHERE email_address = ? AND is_deleted = 0 LIMIT 1;`
	var id string
	var firstName *string
	var lastName *string
	var emailAddress string
	err := db.DB.QueryRow(query, email).Scan(&id, &firstName, &lastName, &emailAddress)
	if err != nil {
		return "", nil, nil, "", err
	}
	return id, firstName, lastName, emailAddress, nil
}

func GetUserID(email string) (string, error) {
	log.Print(email)
	query := `SELECT id, FROM users WHERE email_address = ? AND is_deleted = 0 LIMIT 1;`
	var id string
	err := db.DB.QueryRow(query, email).Scan(&id)
	if err != nil {
		return "", err
	}
	return id, nil
}

func CheckEmailInDB(email string) (bool, error) {
	var exists bool
	query := `SELECT EXISTS (
		SELECT 1 FROM users WHERE email_address = ? AND is_deleted = 0);`
	err := db.DB.QueryRow(query, email).Scan(&exists)
	if err != nil {
		return false, err
	}
	return exists, nil
}

func GetUserIDFromEmail(email string) (string, error) {
	log.Print(email)
	query := `SELECT id
				FROM (
					SELECT id, 1 AS priority
					FROM users
					WHERE email_address = ?
					AND is_deleted = 0
				) t
				ORDER BY priority ASC
				LIMIT 1;
						`

	var id string
	err := db.DB.QueryRow(query, email).Scan(&id)
	if err != nil {
		log.Println("Hello")

		return "", err
	}

	return id, nil
}
