<?php

namespace App\Services;

use App\Models\Terminal;
use App\Models\TerminalSyncLog;
use App\Jobs\SyncTerminalConfigJob;

/**
 * 终端配置同步服务
 */
class TerminalSyncService
{
    /**
     * 同步终端配置
     *
     * @param Terminal $terminal
     * @return TerminalSyncLog
     */
    public function syncConfiguration(Terminal $terminal): TerminalSyncLog
    {
        // 创建同步日志记录
        $log = TerminalSyncLog::create([
            'terminal_id' => $terminal->id,
            'status' => 'pending',
            'config_snapshot' => $this->getConfigSnapshot($terminal),
        ]);

        // 触发异步同步任务
        dispatch(new SyncTerminalConfigJob($terminal, $log));

        return $log;
    }

    /**
     * 获取终端配置快照
     *
     * @param Terminal $terminal
     * @return array
     */
    public function getConfigSnapshot(Terminal $terminal): array
    {
        // 加载关联数据
        $terminal->load(['knowledgeBases', 'prompt']);

        return [
            'terminal' => [
                'id' => $terminal->id,
                'name' => $terminal->name,
                'code' => $terminal->code,
                'ip_address' => $terminal->ip_address,
                'station_id' => $terminal->station_id,
                'diagram_url' => $terminal->diagram_url,
                'display_config' => $terminal->display_config,
            ],
            'knowledge_bases' => $terminal->knowledgeBases->map(function ($kb) {
                return [
                    'id' => $kb->id,
                    'name' => $kb->name,
                    'priority' => $kb->pivot->priority,
                ];
            })->toArray(),
            'prompt' => $terminal->prompt ? [
                'prompt_template' => $terminal->prompt->prompt_template,
                'variables' => $terminal->prompt->variables,
            ] : null,
        ];
    }

    /**
     * 更新同步状态
     *
     * @param TerminalSyncLog $log
     * @param string $status
     * @param string|null $errorMessage
     * @return void
     */
    public function updateSyncStatus(TerminalSyncLog $log, string $status, ?string $errorMessage = null): void
    {
        $data = ['status' => $status];

        if ($status === 'synced') {
            $data['synced_at'] = now();
        }

        if ($errorMessage) {
            $data['error_message'] = $errorMessage;
        }

        $log->update($data);
    }

    /**
     * 批量同步终端配置
     *
     * @param array $terminalIds
     * @return array
     */
    public function batchSync(array $terminalIds): array
    {
        $logs = [];

        foreach ($terminalIds as $terminalId) {
            $terminal = Terminal::find($terminalId);
            if ($terminal) {
                $logs[] = $this->syncConfiguration($terminal);
            }
        }

        return $logs;
    }
}
