<?php

namespace Database\Factories;

use App\Enums\VehicleLogType;
use App\Models\Guard;
use App\Models\Vehicle;
use App\Models\VehicleLog;
use Illuminate\Database\Eloquent\Factories\Factory;

class VehicleLogFactory extends Factory
{
    protected $model = VehicleLog::class;

    public function definition(): array
    {
        $logType = $this->faker->randomElement([VehicleLogType::ENTRY, VehicleLogType::EXIT]);

        return [
            'vehicle_id' => Vehicle::factory(),
            'guard_id' => Guard::factory(),
            'log_type' => $logType,
            'logged_at' => $this->faker->dateTimeBetween('-30 days', 'now'),
            'purpose' => $this->faker->optional()->randomElement([
                'Office', 'Shopping', 'Medical', 'Visit relatives', 'Delivery', 'Service'
            ]),
            'visitor_details' => $this->faker->optional()->passthrough([
                'name' => $this->faker->name(),
                'phone' => $this->faker->numerify('##########'),
                'purpose' => $this->faker->randomElement(['Personal', 'Business', 'Delivery'])
            ]),
            'outsider_vehicle_details' => $this->faker->optional()->passthrough([
                'registration_no' => $this->generateRegistrationNumber(),
                'make' => $this->faker->randomElement(['Mahindra', 'Tata', 'Maruti']),
                'model' => $this->faker->randomElement(['Bolero', 'Sumo', 'Swift']),
                'driver_name' => $this->faker->name(),
                'driver_phone' => $this->faker->numerify('##########')
            ]),
        ];
    }

    private function generateRegistrationNumber(): string
    {
        $states = ['MH', 'KA', 'TN', 'DL', 'UP', 'GJ', 'RJ', 'WB'];
        $state = $this->faker->randomElement($states);
        $district = $this->faker->numberBetween(1, 99);
        $series = $this->faker->randomLetter() . $this->faker->randomLetter();
        $number = $this->faker->numberBetween(1000, 9999);

        return sprintf('%s%02d%s%04d', $state, $district, $series, $number);
    }

    public function entry(): static
    {
        return $this->state(fn(array $attributes) => [
            'log_type' => VehicleLogType::ENTRY,
        ]);
    }

    public function exit(): static
    {
        return $this->state(fn(array $attributes) => [
            'log_type' => VehicleLogType::EXIT,
        ]);
    }

    public function today(): static
    {
        return $this->state(fn(array $attributes) => [
            'logged_at' => $this->faker->dateTimeBetween('today', 'now'),
        ]);
    }
}
