<?php

namespace Database\Factories;

use App\Models\Address;
use Illuminate\Database\Eloquent\Factories\Factory;
use Random\RandomException;

/**
 * @extends Factory<Address>
 */
class AddressFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     * @throws RandomException
     */
    public function definition(): array
    {
        $professionnal = fake()->boolean();
        $countryId = mt_rand(1, 4); // 1=France, 2=Belgique, 3=Suisse, 4=Canada

        // Génération du nom (personne ou entreprise)
        $name = !$professionnal || fake()->boolean() ? fake()->lastName : null;
        $firstName = !$professionnal || fake()->boolean() ? fake()->firstName : null;

        // Génération du numéro de TVA selon le pays
        $buyerTaxNo = null;
        if ($professionnal) {
            switch ($countryId) {
                case 1: // France
                    $buyerTaxNo = 'FR' . str_pad(random_int(0, 99), 2, '0', STR_PAD_LEFT) . ' ' . str_pad(random_int(0, 999999999), 9, '0', STR_PAD_LEFT);
                    break;
                case 2: // Belgique
                    $buyerTaxNo = 'BE ' . str_pad(random_int(0, 999), 3, '0', STR_PAD_LEFT) . '.' . str_pad(random_int(0, 999), 3, '0', STR_PAD_LEFT) . '.' . str_pad(random_int(0, 999), 3, '0', STR_PAD_LEFT);
                    break;
                case 3: // Suisse
                    $buyerTaxNo = 'CHE-' . str_pad(random_int(0, 999999999), 9, '0', STR_PAD_LEFT) . ' TVA';
                    break;
                case 4: // Canada
                    $buyerTaxNo = 'CA' . str_pad(random_int(0, 999999999), 9, '0', STR_PAD_LEFT);
                    break;
            }
        }

        // Génération du SIREN/SIRET ou équivalent pour la France
        $siren = null;
        if ($professionnal && $countryId == 1) {
            $siren = str_pad(random_int(0, 999999999), 9, '0', STR_PAD_LEFT);
        }

        return [
            'professionnal' => $professionnal,
            'civility' => fake()->boolean() ? 'Mme' : 'M.',
            'name' => $name,
            'firstname' => $firstName,
            'company' => $professionnal ? fake()->company : null,
            'buyer_tax_no' => $buyerTaxNo,
            'siren' => $siren,
            'address' => fake()->streetAddress,
            'addressbis' => fake()->boolean() ? fake()->secondaryAddress : null,
            'bp' => fake()->boolean() ? fake()->numberBetween(100, 900) : null,
            'postal' => fake()->numberBetween(10000, 90000),
            'city' => fake()->city,
            'country_id' => $countryId,
            'phone' => fake()->numberBetween(1000000000, 9000000000),
        ];
    }
}
