package com.lesingle.edu.controller.school;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.annotation.RequireRole;
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.TaskTemplateCreateRequest;
import com.lesingle.edu.dto.response.TaskTemplateResponse;
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.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 学校端 - 任务模板
 */
@Tag(name = "学校端 - 任务模板", description = "School Task Template APIs")
@RestController
@RequestMapping("/api/v1/school/task-templates")
@RequiredArgsConstructor
@RequireRole(UserRole.SCHOOL)
public class SchoolTaskTemplateController {

    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 taskType,
            @RequestParam(required = false) String keyword) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        String typeFilter = StringUtils.hasText(taskType) ? taskType : type;
        Page<TaskTemplate> page = taskTemplateService.getTemplates(tenantId, pageNum, pageSize, typeFilter, 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) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        TaskTemplate template = taskTemplateService.getTemplateById(id);
        if (!template.getTenantId().equals(tenantId)) {
            throw new com.lesingle.edu.common.exception.BusinessException(
                    com.lesingle.edu.common.enums.ErrorCode.FORBIDDEN, "无权访问该模板");
        }
        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));
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新模板")
    @Log(module = LogModule.TASK_TEMPLATE, type = LogOperationType.UPDATE, description = "更新任务模板")
    public Result<TaskTemplateResponse> updateTemplate(
            @PathVariable Long id,
            @RequestBody TaskTemplateCreateRequest request) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        TaskTemplate existing = taskTemplateService.getTemplateById(id);
        if (!existing.getTenantId().equals(tenantId)) {
            throw new com.lesingle.edu.common.exception.BusinessException(
                    com.lesingle.edu.common.enums.ErrorCode.FORBIDDEN, "无权修改该模板");
        }
        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) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        TaskTemplate template = taskTemplateService.getTemplateById(id);
        if (!template.getTenantId().equals(tenantId)) {
            throw new com.lesingle.edu.common.exception.BusinessException(
                    com.lesingle.edu.common.enums.ErrorCode.FORBIDDEN, "无权删除该模板");
        }
        taskTemplateService.deleteTemplate(id);
        return Result.success();
    }
}
