<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;
use App\Imports\DataImport;

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

    protected string $modelName;
    protected string $filePath;
    public $timeout = 3600;
    public $tries = 1;

    /**
     * Create a new job instance.
     */
    public function __construct(string $filePath,string $modelName)
    {
        $this->filePath = $filePath;
        $this->modelName= $modelName;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        ini_set('memory_limit', '512M'); // ✅ 增加記憶體限制
        Log::info('[ImportJob] 開始處理檔案：' . $this->filePath);

        try {
            if (!Storage::exists($this->filePath)) {
                Log::warning('[ImportJob] 檔案不存在：' . $this->filePath);
                return;
            }

            Excel::import(new DataImport($this->modelName), $this->filePath);
            Log::info('[ImportJob] 已提交所有 chunk 匯入任務。');

            Storage::delete($this->filePath);
            Log::info('[ImportJob] 已刪除檔案：' . $this->filePath);
        } catch (\Throwable $e) {
            Log::error("[ImportJob] 匯入失敗：{$e->getMessage()}", [
                'file' => $this->filePath,
                'trace' => $e->getTraceAsString(),
            ]);
        }
    }
}