<?php

namespace App\Actions\Fortify;

use App\Models\Customer;
use App\Models\Operator;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Laravel\Fortify\Contracts\CreatesNewUsers;

class CreateNewUser implements CreatesNewUsers
{
    use PasswordValidationRules;

    /**
     * Validate and create a newly registered user.
     *
     * @param  array<string, string>  $input
     *
     * @throws ValidationException
     */
    public function create(array $input): User
    {
        Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'email' => [
                'required',
                'string',
                'email',
                'max:255',
                Rule::unique(User::class),
                // Never let public signup claim an existing (possibly not-yet-
                // provisioned) customer's email — ensureUser() would later link
                // that account and hand over the customer's portal.
                Rule::unique(Customer::class, 'email'),
                // Nor an operator's — R21: one address must not represent both
                // identities. No dedicated message: Laravel's stock "already
                // taken" line (translated in both languages already) is what
                // the two rules above fall back to as well, and telling a
                // public visitor specifically that an address belongs to
                // STAFF would be a worse leak than the generic refusal every
                // other collision here already gives them.
                Rule::unique(Operator::class, 'email'),
            ],
            // Asked, never inferred. Everything downstream turns on it — the
            // fourteen-day right of withdrawal, the wording of the invoice,
            // whether reverse charge can apply — and a VAT number cannot stand
            // in for it: plenty of businesses have none, and no consumer has
            // one. Required, because the alternative is a field that is empty
            // for most customers and therefore answers nothing.
            'customer_type' => ['required', Rule::in(Customer::TYPES)],
            'password' => $this->passwordRules(),
        ])->validate();

        // Create the user and its linked customer atomically — a public signup is
        // a customer, and the portal (Billing::purchase, Settings, …) needs one.
        // Either both exist or neither, so a failure never orphans a user.
        return DB::transaction(function () use ($input) {
            $user = User::create([
                'name' => $input['name'],
                'email' => $input['email'],
                'password' => Hash::make($input['password']),
            ]);

            Customer::query()->create([
                'user_id' => $user->id,
                'name' => $input['name'],
                'email' => $input['email'],
                'customer_type' => $input['customer_type'],
                'locale' => app()->getLocale(),
                'status' => 'active',
            ]);

            return $user;
        });
    }
}
