<?php

namespace Database\Seeders;

use App\Models\Project;
use App\Models\ProjectTask;
use App\Models\User;
use Illuminate\Database\Seeder;

class ProjectTaskSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $creator = User::whereIn('role', ['admin', 'moderator'])->first();
        $fallbackAssignee = User::where('role', 'on_site_team')->first();

        $template = [
            [
                'title' => 'Confirm next inspection date',
                'description' => 'Coordinate with client and consultant for next site inspection.',
                'status' => 'pending',
                'due_days' => 3,
            ],
            [
                'title' => 'Update material requisition',
                'description' => 'Submit revised material requirements for the next work week.',
                'status' => 'in_progress',
                'due_days' => 5,
            ],
            [
                'title' => 'Close previous snag list',
                'description' => 'Verify all pending snag items and share evidence in report.',
                'status' => 'completed',
                'due_days' => -2,
            ],
        ];

        foreach (Project::with('assignedUsers')->get() as $project) {
            foreach ($template as $task) {
                $assignee = $project->assignedUsers->first() ?? $fallbackAssignee;

                ProjectTask::create([
                    'project_id' => $project->id,
                    'title' => $task['title'],
                    'description' => $task['description'],
                    'status' => $task['status'],
                    'due_date' => now()->addDays($task['due_days'])->toDateString(),
                    'assigned_to_id' => $assignee?->id,
                    'created_by_id' => $creator?->id,
                ]);
            }
        }
    }
}
