package com.lesingle.edu.controller.teacher;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lesingle.edu.common.annotation.RequireRole;
import com.lesingle.edu.common.annotation.Log;
import com.lesingle.edu.common.enums.LogModule;
import com.lesingle.edu.common.enums.LogOperationType;
import com.lesingle.edu.common.enums.UserRole;
import com.lesingle.edu.common.mapper.TaskTemplateMapper;
import com.lesingle.edu.common.response.PageResult;
import com.lesingle.edu.common.response.Result;
import com.lesingle.edu.common.security.SecurityUtils;
import com.lesingle.edu.dto.request.CreateTaskFromTemplateRequest;
import com.lesingle.edu.dto.request.TaskTemplateCreateRequest;
import com.lesingle.edu.dto.response.TaskTemplateResponse;
import com.lesingle.edu.entity.Task;
import com.lesingle.edu.entity.TaskTemplate;
import com.lesingle.edu.service.TaskTemplateService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 教师端 - 任务模板
 */
@Tag(name = "教师端 - 任务模板", description = "教师端任务模板 API")
@RestController
@RequestMapping("/api/v1/teacher/task-templates")
@RequiredArgsConstructor
@RequireRole(UserRole.TEACHER)
public class TeacherTaskTemplateController {

    private final TaskTemplateService taskTemplateService;
    private final TaskTemplateMapper taskTemplateMapper;

    @GetMapping
    @Operation(summary = "获取模板列表")
    public Result<PageResult<TaskTemplateResponse>> getTemplates(
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String keyword) {
        // 教师查询其关联学校（tenant）下的所有模板，包括学校端建立的阅读模版
        Long tenantId = SecurityUtils.getCurrentTenantId();
        Page<TaskTemplate> page = taskTemplateService.getTemplates(tenantId, pageNum, pageSize, type, keyword, false);
        List<TaskTemplateResponse> voList = taskTemplateMapper.toVO(page.getRecords());
        return Result.success(PageResult.of(voList, page.getTotal(), page.getCurrent(), page.getSize()));
    }

    @GetMapping("/default/{type}")
    @Operation(summary = "获取默认模板")
    public Result<TaskTemplateResponse> getDefaultTemplate(@PathVariable String type) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        TaskTemplate template = taskTemplateService.getDefaultTemplate(tenantId, type);
        return template != null ? Result.success(taskTemplateMapper.toVO(template)) : Result.success(null);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取模板详情")
    public Result<TaskTemplateResponse> getTemplate(@PathVariable Long id) {
        TaskTemplate template = taskTemplateService.getTemplateById(id);
        return Result.success(taskTemplateMapper.toVO(template));
    }

    @PostMapping
    @Operation(summary = "创建模板")
    @Log(module = LogModule.TASK_TEMPLATE, type = LogOperationType.CREATE, description = "创建任务模板")
    public Result<TaskTemplateResponse> createTemplate(@Valid @RequestBody TaskTemplateCreateRequest request) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        Long userId = SecurityUtils.getCurrentUserId();
        TaskTemplate template = taskTemplateService.createTemplate(tenantId, userId, request);
        return Result.success(taskTemplateMapper.toVO(template));
    }

    @PostMapping("/from-template")
    @Operation(summary = "从模板创建任务")
    @Log(module = LogModule.TASK_TEMPLATE, type = LogOperationType.CREATE, description = "从模板创建任务")
    public Result<Task> createFromTemplate(@Valid @RequestBody CreateTaskFromTemplateRequest request) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        Long userId = SecurityUtils.getCurrentUserId();
        Task task = taskTemplateService.createTaskFromTemplate(tenantId, userId, request.getTemplateId(), request);
        return Result.success(task);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新模板")
    @Log(module = LogModule.TASK_TEMPLATE, type = LogOperationType.UPDATE, description = "更新任务模板")
    public Result<TaskTemplateResponse> updateTemplate(
            @PathVariable Long id,
            @RequestBody TaskTemplateCreateRequest request) {
        TaskTemplate template = taskTemplateService.updateTemplate(id, request);
        return Result.success(taskTemplateMapper.toVO(template));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除模板")
    @Log(module = LogModule.TASK_TEMPLATE, type = LogOperationType.DELETE, description = "删除任务模板")
    public Result<Void> deleteTemplate(@PathVariable Long id) {
        taskTemplateService.deleteTemplate(id);
        return Result.success();
    }
}
