<?php

namespace App\Filament\Actions;

use App\Models\Terminal;
use App\Services\TerminalSyncService;
use Filament\Tables\Actions\Action;
use Filament\Tables\Actions\BulkAction;
use Filament\Notifications\Notification;

/**
 * 同步终端配置Action
 */
class SyncConfigAction
{
    /**
     * 创建单个终端同步Action
     *
     * @return Action
     */
    public static function make(): Action
    {
        return Action::make('sync')
            ->label('同步配置')
            ->icon('heroicon-o-arrow-path')
            ->color('success')
            ->requiresConfirmation()
            ->modalHeading('同步终端配置')
            ->modalDescription('确定要将配置同步到此终端吗？')
            ->modalSubmitActionLabel('确认同步')
            ->action(function (Terminal $record) {
                $service = app(TerminalSyncService::class);
                $log = $service->syncConfiguration($record);

                Notification::make()
                    ->title('同步任务已启动')
                    ->body("终端 {$record->name} 的配置同步任务已加入队列")
                    ->success()
                    ->send();
            });
    }

    /**
     * 创建批量同步Action
     *
     * @return BulkAction
     */
    public static function makeBulk(): BulkAction
    {
        return BulkAction::make('batchSync')
            ->label('批量同步')
            ->icon('heroicon-o-arrow-path')
            ->color('success')
            ->requiresConfirmation()
            ->modalHeading('批量同步终端配置')
            ->modalDescription(fn ($records) => "确定要同步 {$records->count()} 个终端的配置吗？")
            ->modalSubmitActionLabel('确认同步')
            ->action(function ($records) {
                $service = app(TerminalSyncService::class);
                $terminalIds = $records->pluck('id')->toArray();
                $logs = $service->batchSync($terminalIds);

                Notification::make()
                    ->title('批量同步任务已启动')
                    ->body("已为 " . count($logs) . " 个终端创建同步任务")
                    ->success()
                    ->send();
            })
            ->deselectRecordsAfterCompletion();
    }
}
