<?php

namespace App\Services;

use App\Models\PasswordReset;
use App\Models\User;
use App\Models\UserComunity;
use App\Models\UserUgel;
use App\Repositories\UserRepository;

class UserRecoveryService
{

    protected UserRepository $userRepository;

    public function __construct() {
        $this->userRepository = new UserRepository();
    }

    public function findUser($dni, $email, $ruc = null)
    {
        $user = $this->userRepository->findComunityUserForPasswordRecovery($dni, $email, $ruc);
        if ($user) {
            $user['source'] = 'comunity';
            return $user;
        }

        $user = $this->userRepository->findUserUgelForPasswordRecovery($dni, $email);
        if ($user) {
            $user['source'] = 'ugel';
            return $user;
        }

        return null;
    }

    public function findUserByEmail($email)
    {
        $user = UserComunity::findBy('email', $email);
        if ($user) {
            return $user;
        }

        return UserUgel::findBy('email', $email);
    }


    public function createPasswordReset($email)
    {
        $token = bin2hex(random_bytes(32));
        $now = date('Y-m-d H:i:s');
        $expiresAt = date('Y-m-d H:i:s', strtotime('+30 minutes'));

        $reset = new PasswordReset();
        $reset->email = $email;
        $reset->token = $token;
        $reset->created_at = $now;
        $reset->expires_at = $expiresAt;
        $reset->used = 0;
        $reset->save();

        return $token;
    }

    public function updatePassword($email, $newPassword)
    {
        $hashed = password_hash($newPassword, PASSWORD_DEFAULT);

        $comunityUser = UserComunity::findBy('email', $email);
        if ($comunityUser) {
            return $this->updateUserPasswordById($comunityUser->user_id, $hashed);
        }

        $ugelUser = UserUgel::findBy('email', $email);
        if ($ugelUser) {
            return $this->updateUserPasswordById($ugelUser->user_id, $hashed);
        }

        return false;
    }

    private function updateUserPasswordById($userId, $hashedPassword)
    {
        $user = User::find($userId);
        if (!$user) return false;

        $user->password = $hashedPassword;
        return $user->save();
    }



}