<?php

namespace Database\Factories;

use App\Enums\NocTrackingStatus;
use App\Enums\WorkInternalStatus;
use App\Enums\WorkPriority;
use App\Enums\WorkStatus;
use App\Models\Project;
use App\Models\Site;
use App\Models\Work;
use App\Models\WorkType;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

/**
 * @extends Factory<Work>
 */
class WorkFactory extends Factory
{
    protected $model = Work::class;

    public function configure(): static
    {
        return $this->afterCreating(function (Work $work): void {
            $site = $work->site;
            if ($site === null) {
                return;
            }
            if ($site->project_id === null) {
                $site->project_id = Project::factory()->create()->id;
                $site->save();
            }
            $projectId = (int) $site->project_id;
            $ok = WorkType::query()
                ->whereKey($work->work_type_id)
                ->where('project_id', $projectId)
                ->exists();
            if ($ok) {
                return;
            }
            $replacementId = WorkType::query()->where('project_id', $projectId)->inRandomOrder()->value('id');
            if ($replacementId === null) {
                $replacementId = WorkType::factory()->create(['project_id' => $projectId])->id;
            }
            $work->update(['work_type_id' => $replacementId]);
        });
    }

    /**
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'ot' => Str::upper($this->faker->unique()->bothify('OT-####-???')),
            'work_status' => $this->faker->randomElement(WorkStatus::cases())->value,
            'scale_datetime' => $this->faker->dateTimeBetween('-3 months', 'now'),
            'clearance_datetime' => $this->faker->optional(0.6)->dateTimeBetween('-3 months', 'now'),
            'sla_hours' => $this->faker->randomElement([2, 4, 6, 8, 12, 24, 48]),
            'priority' => $this->faker->randomElement(WorkPriority::cases())->value,
            'observation' => $this->faker->optional(0.5)->sentence(10),
            'scheduled_date' => $this->faker->optional(0.7)->dateTimeBetween('now', '+1 month'),
            'internal_status' => $this->faker->randomElement(WorkInternalStatus::cases())->value,
            'site_id' => Site::factory(),
            'work_type_id' => WorkType::factory(),
            'noc_id' => null,
            'technician_id' => null,
            'coordinator_id' => null,
            'noc_tracking_status' => NocTrackingStatus::PENDIENTE->value,
            'noc_comment' => $this->faker->optional(0.3)->sentence(8),
        ];
    }
}
