<?php
namespace Database\Factories;

use App\Enums\StatutMission;
use App\Enums\StatutCandidat;
use App\Models\Mission;
use App\Models\Besoin;
use App\Models\Candidat;
use App\Models\Client;
use App\Models\User;
use App\Models\Ville;
use Illuminate\Database\Eloquent\Factories\Factory;

class MissionFactory extends Factory
{
    protected $model = Mission::class;

    public function definition(): array
    {
        $ville = Ville::factory()->active()->create();
        $clientUser = User::factory()->client()->create();
        $client = Client::factory()->create([
            'user_id'  => $clientUser->id,
            'ville_id' => $ville->id,
        ]);
        $besoin = Besoin::factory()->create([
            'client_id' => $client->id,
            'ville_id'  => $ville->id,
        ]);
        $candidatUser = User::factory()->candidat()->create();
        $candidat = Candidat::factory()->create([
            'user_id'  => $candidatUser->id,
            'ville_id' => $ville->id,
            'statut'   => StatutCandidat::EN_MISSION->value,
        ]);

        return [
            'reference' => 'MSN-' . date('Y') . '-' . str_pad(fake()->unique()->numberBetween(1, 9999), 4, '0', STR_PAD_LEFT),
            'besoin_id' => $besoin->id,
            'candidat_id' => $candidat->id,
            'client_id' => $client->id,
            'assigne_par' => null,
            'type_service' => 'menage_residente',
            'date_debut' => now()->subDays(30),
            'date_fin_prevue' => now()->addDays(30),
            'date_fin_reelle' => null,
            'statut' => StatutMission::ACTIVE->value,
            'salaire_mensuel' => fake()->numberBetween(50000, 200000),
            'tarif_agence' => fake()->numberBetween(10000, 50000),
            'frequence_paiement' => 'mensuel',
        ];
    }

    public function active(): static
    {
        return $this->state(fn (array $attributes) => ['statut' => StatutMission::ACTIVE->value]);
    }

    /**
     * Alias de active() pour compatibilité avec les tests Phase 3.
     * StatutMission::ACTIVE->value = 'active' (pas 'en_cours').
     */
    public function enCours(): static
    {
        return $this->state(fn (array $attributes) => [
            'statut' => StatutMission::ACTIVE->value,
        ]);
    }

    public function terminee(): static
    {
        return $this->state(fn (array $attributes) => [
            'statut' => StatutMission::TERMINEE->value,
            'date_fin_reelle' => now(),
        ]);
    }

    public function planifiee(): static
    {
        return $this->state(fn (array $attributes) => [
            'statut' => StatutMission::PLANIFIEE->value,
            'date_debut' => now()->addDays(7),
            'date_fin_prevue' => now()->addDays(37),
            'date_fin_reelle' => null,
        ]);
    }

    public function suspendue(): static
    {
        return $this->state(fn (array $attributes) => ['statut' => StatutMission::SUSPENDUE->value]);
    }
}
