<?php

declare(strict_types=1);

namespace App\Http\Controllers\Account;

use App\Http\Controllers\Controller;
use App\Http\Requests\Account\RegisterRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Mtc\MercuryDataModels\Customer;

class RegisterController extends Controller
{
    public function store(RegisterRequest $request): JsonResponse
    {
        $existing = $request->existingCustomer();

        if ($existing !== null && !empty($existing->password)) {
            throw ValidationException::withMessages([
                'email' => __('An account with this email already exists.'),
            ]);
        }

        $customer = $existing ?? new Customer();

        $customer->fill($request->safe()->except(['password']));
        $customer->password = $request->input('password');
        $customer->save();

        Auth::guard('customer')->login($customer);
        $request->session()->regenerate();

        return new JsonResponse([
            'customer' => $customer->fresh(),
        ], 201);
    }
}
