<?php

namespace App\Jobs;

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;
use Illuminate\Support\Facades\Storage;
use App\Services\ExcelService;
use Illuminate\Support\Facades\Notification;
use App\Notifications\ImportCompletedNotification;

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

    protected $filePath;
    protected $importClass;
    protected $userId;
    protected $options;

    public function __construct($filePath, $importClass, $userId, $options = [])
    {
        $this->filePath = $filePath;
        $this->importClass = $importClass;
        $this->userId = $userId;
        $this->options = $options;
    }

    public function handle()
    {
        try {
            Log::info('Starting import job', [
                'file' => $this->filePath,
                'import_class' => $this->importClass,
                'user_id' => $this->userId,
            ]);

            $excelService = app(ExcelService::class);
            
            $file = Storage::disk('local')->path($this->filePath);
            
            $results = $excelService->import($file, $this->importClass, $this->options);
            
            // Delete the file after import
            Storage::disk('local')->delete($this->filePath);
            
            // Send notification to user
            $user = \App\Models\User::find($this->userId);
            if ($user) {
                Notification::send($user, new ImportCompletedNotification($results));
            }
            
            Log::info('Import job completed', [
                'results' => $results,
            ]);
            
            return $results;
            
        } catch (\Exception $e) {
            Log::error('Import job failed', [
                'error' => $e->getMessage(),
                'file' => $this->filePath,
            ]);
            
            throw $e;
        }
    }

    public function failed(\Exception $exception)
    {
        Log::error('Import job failed', [
            'error' => $exception->getMessage(),
            'file' => $this->filePath,
        ]);
        
        // Send notification to user about failure
        $user = \App\Models\User::find($this->userId);
        if ($user) {
            Notification::send($user, new ImportCompletedNotification([
                'success_count' => 0,
                'error_count' => 1,
                'errors' => [$exception->getMessage()],
            ]));
        }
    }
}
