<?php

namespace Database\Factories;

use App\Models\Company;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends Factory<Company>
 */
class CompanyFactory extends Factory
{
    protected $model = Company::class;

    public function definition(): array
    {
        return [
            'cnpj' => $this->cnpjValido(),
            'razao_social' => $this->faker->company().' LTDA',
            'nome_fantasia' => $this->faker->company(),
            'ie' => (string) $this->faker->numberBetween(100000000, 999999999),
            'uf' => $this->faker->randomElement(['SP', 'MG', 'PR', 'RS', 'BA']),
            'email' => $this->faker->companyEmail(),
            'plano' => 'mensal',
            'is_active' => true,
            'assinatura_expira_em' => now()->addYear(),
        ];
    }

    public function semAssinatura(): static
    {
        return $this->state(fn () => ['assinatura_expira_em' => now()->subDay()]);
    }

    /** Gera um CNPJ com dígitos verificadores corretos. */
    private function cnpjValido(): string
    {
        $base = '';

        for ($i = 0; $i < 12; $i++) {
            $base .= random_int(0, 9);
        }

        foreach ([12, 13] as $posicao) {
            $soma = 0;
            $peso = $posicao - 7;

            for ($i = 0; $i < $posicao; $i++) {
                $soma += (int) $base[$i] * $peso;
                $peso = $peso === 2 ? 9 : $peso - 1;
            }

            $resto = $soma % 11;
            $base .= $resto < 2 ? 0 : 11 - $resto;
        }

        return $base;
    }
}
