<?php

namespace App\Http\Controllers\v1\Tenancy\User;

use App\Http\Controllers\Controller;
use App\Http\Requests\Tenancy\User\UpdateUserPasswordRequest;
use App\Models\Tenancy\User;
use App\Models\Tenant;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class UpdateUserPasswordController extends Controller
{
    public function __invoke(UpdateUserPasswordRequest $request): Response
    {
        $user = \auth()->user();
        $merchantPermissions = Auth::guard('api')->user()->getPermissionNames();
        $tenantsIdsToUpdate = Tenant::whereIn('unique_name', $merchantPermissions)
            ->pluck('id');
        $password = Hash::make($request->password);
        tenancy()->runForMultiple($tenantsIdsToUpdate, function () use ($password, $user) {
            $user = User::where('email', $user->email)->first();
            if ($user) {
                $user->password = $password;
                $user->save();
            }
        });

        return $this->ok($user);
    }
}
