<?php

namespace App\Jobs;

use App\Models\Project;
use App\Models\Page;
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\Log;

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

    public $timeout = 600;
    public $tries = 1;

    protected Project $project;

    public function __construct(Project $project)
    {
        $this->project = $project;
    }

    public function handle(): void
    {
        Log::info('Processing project', ['project_id' => $this->project->id]);

        try {
            // Update project status
            $this->project->update(['status' => 'processing']);

            // Dispatch jobs to process pages in batches
            $batchSize = config('services.seo.batch_size', 10);
            $pages = $this->project->pages()->where('status', 'pending')->get();

            foreach ($pages->chunk($batchSize) as $batch) {
                foreach ($batch as $page) {
                    ProcessPage::dispatch($page)->onQueue('default');
                }

                // Small delay between batches
                sleep(1);
            }

            Log::info('Project processing jobs dispatched', [
                'project_id' => $this->project->id,
                'total_pages' => $pages->count(),
            ]);

        } catch (\Exception $e) {
            Log::error('Project processing failed', [
                'project_id' => $this->project->id,
                'error' => $e->getMessage(),
            ]);

            $this->project->update([
                'status' => 'failed',
                'error_message' => $e->getMessage(),
            ]);
        }
    }
}
