<?php

class Reset_password_model extends Cf_Model
{
    public const FORGOT_PASSWORD_URL = '/auth/password/forgot';
    public const RESET_PASSWORD_URL = '/auth/password/reset';

    public function __construct()
    {
        parent::__construct();
    }

    public function requestResetLink($username): array
    {
        try {
            $message = $this->getRestClient()->post(self::FORGOT_PASSWORD_URL . '/' . $username);
            return ['success' => true, 'message' => $message];
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    public function resetPasswordByToken(string $token, ?string $password = null): array
    {
        try {
            $response = $this->getRestClient()->post(self::RESET_PASSWORD_URL . '/' . $token, [
                'password' => $password,
            ]);
            return ['success' => true, 'message' => $response];
        } catch (HttpClient_NotFound | HttpClient_TooManyRequests $e) {
            return ['success' => false, 'tokenNotFound' => true, 'message' => $e->getMessage()];
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    public function invalidateResetPasswordToken(string $token): array
    {
        try {
            $message = $this->getRestClient()->delete(self::RESET_PASSWORD_URL . '/' . $token);
            return ['success' => true, 'message' => $message];
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }
}
