<?php

namespace Kylin\Export\Services;

use Kylin\Export\Models\Export;
use Kylin\Export\Traits\ExportAudit;

/**
 * 导出服务
 *
 * 管理数据导出任务的生命周期：创建、执行、完成、失败。
 *
 * 合规要求：
 *  - 依据等保 2.0 (GB/T 22239) 8.1.4.6，导出操作需记录审计日志
 */
class ExportService
{
    use ExportAudit;

    public function create(string $type, string $filename, ?array $filters = null, ?int $userId = null): Export
    {
        $export = Export::create([
            'type' => $type,
            'filename' => $filename,
            'status' => 'pending',
            'filters' => $filters,
            'user_id' => $userId,
        ]);

        // 审计日志：导出创建
        $this->auditExport('export_created', $export->id, [
            'type' => $type,
            'filename' => $filename,
            'user_id' => $userId,
        ]);

        return $export;
    }

    public function markProcessing(Export $export): void
    {
        $export->update(['status' => 'processing']);
    }

    public function markCompleted(Export $export, string $path, int $rows): void
    {
        $export->update(['status' => 'completed', 'path' => $path, 'rows' => $rows]);

        // 审计日志：导出完成
        $this->auditExport('export_completed', $export->id, [
            'type' => $export->type,
            'filename' => $export->filename,
            'rows' => $rows,
        ]);
    }

    public function markFailed(Export $export, string $error): void
    {
        $export->update(['status' => 'failed', 'error' => $error]);

        // 审计日志：导出失败
        $this->auditExport('export_failed', $export->id, [
            'type' => $export->type,
            'filename' => $export->filename,
            'error' => $error,
        ]);
    }

    /**
     * 审计导出下载操作
     */
    public function auditExportDownload(Export $export): void
    {
        $this->auditExport('export_downloaded', $export->id, [
            'type' => $export->type,
            'filename' => $export->filename,
            'user_id' => $export->user_id,
        ]);
    }
}