<?php

namespace App\Jobs;

use App\Repositories\ReportsRepository;
use App\Services\ReportsService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    protected string $type;

    protected array $params;

    public function __construct(string $type, array $params = [])
    {
        $this->type = $type;
        $this->params = $params;
    }

    public function handle(ReportsService $service, ReportsRepository $repo)
    {
        if ($this->type === 'revenue') {
            $rows = $repo->revenueByMonth($this->params['from'] ?? null, $this->params['to'] ?? null);

            $csv = "Month,Total\n";
            foreach ($rows as $row) {
                $csv .= sprintf("%s,%s\n", $row->month, $row->total);
            }

            $filename = $this->params['filename'] ?? ('revenue_'.now()->format('YmdHis').'.csv');
            $path = $service->storeExportCsv($filename, $csv);

            $service->logExport('revenue', ['path' => $path]);
        }

        // Additional report types (customers, activity) can be added here
    }
}
