<?php

declare(strict_types=1);

namespace Database\Factories;

use App\Models\OrderRiskAssessment;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

/** @extends Factory<OrderRiskAssessment> */
class OrderRiskAssessmentFactory extends Factory
{
    protected $model = OrderRiskAssessment::class;

    /** @return array<string, mixed> */
    public function definition(): array
    {
        $score = fake()->numberBetween(0, 100);

        return [
            'order_id' => null,
            'user_id' => User::factory(),
            'risk_score' => $score,
            'risk_level' => match (true) {
                $score >= 85 => 'critical',
                $score >= 60 => 'high',
                $score >= 30 => 'medium',
                default => 'low',
            },
            'checks' => [
                'disposable_email' => ['score' => 0, 'details' => 'Email domain is legitimate'],
                'velocity' => ['score' => 0, 'details' => 'No suspicious activity'],
                'ip_country_mismatch' => ['score' => 0, 'details' => 'IP matches billing country'],
                'email_domain_age' => ['score' => 0, 'details' => 'Email domain has MX records'],
                'previous_flags' => ['score' => 0, 'details' => 'No previous flags'],
            ],
            'auto_action' => match (true) {
                $score >= 85 => 'reject',
                $score >= 60 => 'hold',
                default => 'approve',
            },
        ];
    }

    public function low(): static
    {
        return $this->state(fn (): array => [
            'risk_score' => fake()->numberBetween(0, 29),
            'risk_level' => 'low',
            'auto_action' => 'approve',
        ]);
    }

    public function medium(): static
    {
        return $this->state(fn (): array => [
            'risk_score' => fake()->numberBetween(30, 59),
            'risk_level' => 'medium',
            'auto_action' => 'approve',
        ]);
    }

    public function high(): static
    {
        return $this->state(fn (): array => [
            'risk_score' => fake()->numberBetween(60, 84),
            'risk_level' => 'high',
            'auto_action' => 'hold',
        ]);
    }

    public function critical(): static
    {
        return $this->state(fn (): array => [
            'risk_score' => fake()->numberBetween(85, 100),
            'risk_level' => 'critical',
            'auto_action' => 'reject',
        ]);
    }

    public function reviewed(): static
    {
        return $this->state(fn (): array => [
            'reviewed_by' => User::factory(),
            'reviewed_at' => now(),
        ]);
    }
}
