<?php

namespace Database\Factories;

use App\Enums\DailyPatrolSummaryStatus;
use App\Models\DailyPatrolSummary;
use App\Models\Guard;
use Illuminate\Database\Eloquent\Factories\Factory;

class DailyPatrolSummaryFactory extends Factory
{
    protected $model = DailyPatrolSummary::class;

    public function definition(): array
    {
        $patrolDate = $this->faker->dateTimeBetween('-30 days', 'now');
        $totalLocations = $this->faker->numberBetween(10, 30);
        $completedLocations = $this->faker->numberBetween(0, $totalLocations);
        $missedLocations = $totalLocations - $completedLocations;
        $status = $this->faker->randomElement(DailyPatrolSummaryStatus::cases());
        
        $startTime = $this->faker->dateTimeBetween($patrolDate->format('Y-m-d') . ' 06:00:00', $patrolDate->format('Y-m-d') . ' 08:00:00');
        $endTime = null;
        
        if ($status === DailyPatrolSummaryStatus::COMPLETED) {
            $endTime = $this->faker->dateTimeBetween($startTime, $patrolDate->format('Y-m-d') . ' 23:59:59');
        }
        
        return [
            'guard_id' => Guard::factory(),
            'patrol_date' => $patrolDate->format('Y-m-d'),
            'total_locations' => $totalLocations,
            'completed_locations' => $completedLocations,
            'missed_locations' => $missedLocations,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'status' => $status,
            'notes' => $this->faker->optional()->sentence(),
        ];
    }

    public function notStarted(): static
    {
        return $this->state(fn (array $attributes) => [
            'status' => DailyPatrolSummaryStatus::NOT_STARTED,
            'start_time' => null,
            'end_time' => null,
        ]);
    }

    public function started(): static
    {
        return $this->state(fn (array $attributes) => [
            'status' => DailyPatrolSummaryStatus::STARTED,
            'end_time' => null,
        ]);
    }

    public function completed(): static
    {
        return $this->state(function (array $attributes) {
            $startTime = $this->faker->dateTimeBetween('-1 day', '-8 hours');
            return [
                'status' => DailyPatrolSummaryStatus::COMPLETED,
                'start_time' => $startTime,
                'end_time' => $this->faker->dateTimeBetween($startTime, 'now'),
            ];
        });
    }

    public function today(): static
    {
        return $this->state(fn (array $attributes) => [
            'patrol_date' => now()->format('Y-m-d'),
            'start_time' => $this->faker->dateTimeBetween('today 06:00:00', 'today 08:00:00'),
        ]);
    }
}