package com.writeoff.module.export.controller;

import com.writeoff.common.api.ApiResponse;
import com.writeoff.common.api.PageResult;
import com.writeoff.module.export.dto.CreateExportTaskRequest;
import com.writeoff.module.export.model.ExportTaskInfo;
import com.writeoff.module.export.service.ExportTaskService;
import com.writeoff.security.DataScopeType;
import com.writeoff.security.RequirePermission;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/api/export-tasks")
public class ExportTaskController {
    private final ExportTaskService exportTaskService;

    public ExportTaskController(ExportTaskService exportTaskService) {
        this.exportTaskService = exportTaskService;
    }

    @GetMapping
    @RequirePermission(value = "export.task.read", dataScope = DataScopeType.TENANT, auditAction = "EXPORT_TASK_LIST")
    public ApiResponse<PageResult<ExportTaskInfo>> list() {
        return ApiResponse.success(exportTaskService.list());
    }

    @PostMapping
    @RequirePermission(value = "export.task.manage", dataScope = DataScopeType.TENANT, auditAction = "EXPORT_TASK_CREATE")
    public ApiResponse<Map<String, Object>> create(@RequestBody @Valid CreateExportTaskRequest request) {
        return ApiResponse.success(exportTaskService.create(request));
    }

    @PostMapping("/{id}/refresh-token")
    @RequirePermission(value = "export.task.manage", dataScope = DataScopeType.TENANT, auditAction = "EXPORT_TASK_REFRESH_TOKEN")
    public ApiResponse<Map<String, Object>> refreshToken(@PathVariable("id") Long id) {
        return ApiResponse.success(exportTaskService.refreshDownloadToken(id));
    }

    @GetMapping("/{id}/download")
    @RequirePermission(value = "export.task.download", dataScope = DataScopeType.TENANT, auditAction = "EXPORT_TASK_DOWNLOAD")
    public ApiResponse<Map<String, Object>> download(@PathVariable("id") Long id,
                                                     @RequestParam("token") String token) {
        return ApiResponse.success(exportTaskService.download(id, token));
    }
}
