<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\TaskTemplate;
use App\Models\TaskTemplateDay;
use App\Models\Task;
use Carbon\Carbon;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    use WithoutModelEvents;

    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        $user = User::factory()->create([
            'name' => 'Demo User',
            'email' => 'test@example.com',
            'password' => bcrypt('password')
        ]);

        $gym = TaskTemplate::create(['user_id' => $user->id, 'title' => 'Gym', 'description' => 'Weight lifting']);
        $gym->days()->createMany([
            ['day_of_week' => 1],
            ['day_of_week' => 3],
            ['day_of_week' => 5],
        ]);

        $cleaning = TaskTemplate::create(['user_id' => $user->id, 'title' => 'House cleaning', 'description' => 'Vacuum and mop']);
        $cleaning->days()->createMany([
            ['day_of_week' => 6],
            ['day_of_week' => 7],
        ]);
        
        $start = Carbon::now()->subDays(30);
        $end = Carbon::now()->addDays(7);
        $statuses = ['todo', 'doing', 'done', 'tomorrow'];

        for ($date = $start->copy(); $date->lte($end); $date->addDay()) {
            // Monday=1, Sunday=7
            $dayOfWeek = $date->dayOfWeekIso; 
            
            $templatesForDay = TaskTemplateDay::where('day_of_week', $dayOfWeek)
                                              ->pluck('task_template_id');

            foreach ($templatesForDay as $tplId) {
                $status = 'todo';
                if ($date->startOfDay()->isPast()) {
                    $status = (rand(1, 10) > 3) ? 'done' : $statuses[array_rand($statuses)];
                }
                
                Task::create([
                    'user_id' => $user->id,
                    'task_template_id' => $tplId,
                    'date' => $date->toDateString(),
                    'status' => $status
                ]);
            }
        }
    }
}
