<?php

namespace App\Jobs;

use App\Models\Project;
use App\Models\User;
use App\Services\ReportGenerator;
use App\DTO\ReportFilters;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;

class SendScheduledReport implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;
    public int $backoff = 60;

    public function handle(): void
    {
        // Get users who want to receive scheduled reports
        $users = User::where('receive_reports', true)
            ->whereHas('projects')
            ->with('projects')
            ->get();

        foreach ($users as $user) {
            foreach ($user->projects as $project) {
                $filters = new ReportFilters();
                $filters->entityTypes = ['phases', 'features', 'inspections', 'issues', 'tasks'];

                $generator = new ReportGenerator($project, $filters);
                $data = $generator->generate();

                Mail::to($user)->send(new \App\Mail\ScheduledReportMail(
                    $project,
                    $user,
                    $data,
                    $filters
                ));
            }
        }
    }
}