<?php

namespace App\Actions;

use Filament\Actions\Action;
use Illuminate\Support\Facades\Log;
use App\Services\TemplateService;

class DownloadTemplateAction extends Action
{
    protected $modelName;
    protected $filename;

    public static function makeTemplate($model, $filename = null): static
    {
        $action = static::make('download_template');
        $action->modelName = $model;
        $action->filename = $filename;
        return $action;
    }

    protected function setUp(): void
    {
        parent::setUp();

        $this
            ->label('Télécharger canevas')
            ->icon('heroicon-o-document-arrow-down')
            ->color('warning')
            ->action(function () {
                try {
                    $filename = $this->filename ?? 'template_' . $this->modelName . '_' . date('Y-m-d') . '.xlsx';
                    
                    Log::info('Starting template download', [
                        'model' => $this->modelName,
                        'filename' => $filename,
                    ]);
                    
                    $templateService = new TemplateService([], [], [], []);
                    return $templateService->generateTemplate($this->modelName, $filename);
                    
                } catch (\Exception $e) {
                    Log::error('Template download failed', [
                        'error' => $e->getMessage(),
                        'model' => $this->modelName,
                    ]);
                    
                    return response()->json([
                        'error' => $e->getMessage(),
                    ], 500);
                }
            });
    }

    public function withFilename($filename): self
    {
        $this->filename = $filename;
        return $this;
    }
}
