<?php

declare(strict_types=1);

namespace App\Http\Controllers\Account;

use App\Http\Controllers\Controller;
use App\Http\Requests\Account\PasswordEmailRequest;
use App\Http\Requests\Account\PasswordResetRequest;
use App\Http\Requests\Account\UpdatePasswordRequest;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Password;
use Illuminate\Validation\ValidationException;
use Mtc\MercuryDataModels\Customer;

class PasswordController extends Controller
{
    public function email(PasswordEmailRequest $request): JsonResponse
    {
        $status = Password::broker('customers')->sendResetLink(
            $request->only('email')
        );

        return new JsonResponse([
            'status' => __($status),
        ], $status === Password::RESET_LINK_SENT ? 200 : 422);
    }

    public function reset(PasswordResetRequest $request): JsonResponse
    {
        $status = Password::broker('customers')->reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function (Customer $customer, string $password): void {
                $customer->forceFill([
                    'password' => $password,
                    'remember_token' => null,
                ])->save();

                Event::dispatch(new PasswordReset($customer));
            }
        );

        if ($status !== Password::PASSWORD_RESET) {
            throw ValidationException::withMessages([
                'email' => [__($status)],
            ]);
        }

        return new JsonResponse([
            'status' => __($status),
        ]);
    }

    public function update(UpdatePasswordRequest $request): JsonResponse
    {
        /** @var Customer $customer */
        $customer = Auth::guard('customer')->user();
        $customer->forceFill([
            'password' => $request->input('password'),
        ])->save();

        return new JsonResponse(null, 204);
    }
}
