<?php

namespace SHServ\Models;

use \SHServ\Entities\User;
use \SHServ\Entities\Profile;

class Auth extends \SHServ\Middleware\Model {
	public function signup(String $email, String $password) {
		$user = app() -> factory -> creator() -> create_user(
			app() -> utils -> gen_alias_from_email($email), 
			$email, 
			$password
		);

		if($user) {
			$profile = app() -> factory -> creator() -> create_profile($user -> id());
		}

		return $user;
	}

	public function signin(String $email, String $password) {
		$user = app() -> factory -> getter() -> get_user_by("email", $email);

		if(!$user) {
			return false;
		}

		$hash = $user -> get("password");

		if(password_verify($password, $hash)) {
			if(password_needs_rehash($hash, PASSWORD_ARGON2ID)) {
				$user -> set("password", password_hash($password, PASSWORD_ARGON2ID)) -> update();
			}
			return app() -> sessions -> init_session($user -> id());
		}

		// Fallback для legacy SHA1 хешей (прозрачная миграция)
		if(sha1($password) === $hash) {
			$user -> set("password", password_hash($password, PASSWORD_ARGON2ID)) -> update();
			return app() -> sessions -> init_session($user -> id());
		}

		return false;
	}

	public function signout() {
		return app() -> sessions -> close_current_session();
	}

	public function remove_session(Int $uid) {
		
	}
}