package com.drinkool.models;

import com.drinkool.utils.PhoneValidator;
import com.password4j.Password;
import io.quarkus.hibernate.orm.panache.PanacheEntity;
import jakarta.persistence.*;
import jakarta.transaction.*;
import jakarta.ws.rs.BadRequestException;
import java.util.UUID;

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "users")
public abstract class User extends PanacheEntity {

	@Column(nullable = false)
	public String name;

	@Column(nullable = false)
	public String phone;

	@Column(nullable = false, length = 1024)
	public String hashedPassword;

	public User() {
		super();
	}

	@Transactional
	public void signup(String phone) {
		this.signup(phone, phone, UUID.randomUUID().toString().substring(0, 32));
	}

	@Transactional
	public void signup(String name, String phone, String rawPassword) {
		this.name = name;

		if (!PhoneValidator.isValidInternationalPhone(phone)) {
			throw new BadRequestException("InvalidPhoneNumber");
		} else {
			this.phone = phone;
		}

		this.hashedPassword = Password.hash(rawPassword).withArgon2().getResult();

		this.persist();
	}

	public boolean login(String rawPassword) {
		if (this.hashedPassword == null) return false;

		return Password.check(rawPassword, this.hashedPassword).withArgon2();
	}
}
