package com.lesingle.edu.controller.admin;

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.response.PageResult;
import com.lesingle.edu.common.response.Result;
import com.lesingle.edu.dto.request.ResourceLibraryCreateRequest;
import com.lesingle.edu.dto.request.ResourceLibraryUpdateRequest;
import com.lesingle.edu.dto.request.ResourceItemCreateRequest;
import com.lesingle.edu.dto.request.ResourceItemUpdateRequest;
import com.lesingle.edu.dto.response.ResourceLibraryResponse;
import com.lesingle.edu.dto.response.ResourceItemResponse;
import com.lesingle.edu.entity.ResourceItem;
import com.lesingle.edu.entity.ResourceLibrary;
import com.lesingle.edu.service.ResourceLibraryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 资源库控制器（超管端）
 */
@RestController
@RequestMapping("/api/v1/admin/resources")
@RequiredArgsConstructor
@Tag(name = "超管端 - 资源库")
public class AdminResourceController {

    private final ResourceLibraryService resourceLibraryService;
    private final ObjectMapper objectMapper;

    // ==================== 资源库管理 ====================

    @GetMapping("/libraries")
    @Operation(summary = "分页查询资源库")
    public Result<PageResult<ResourceLibraryResponse>> findAllLibraries(
            @RequestParam(required = false) String libraryType,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Page<ResourceLibrary> page = resourceLibraryService.findAllLibraries(libraryType, keyword, pageNum, pageSize);

        List<ResourceLibraryResponse> responses = page.getRecords().stream()
                .map(this::toLibraryResponse)
                .collect(Collectors.toList());

        return Result.success(PageResult.of(responses, page.getTotal(), page.getCurrent(), page.getSize()));
    }

    @GetMapping("/libraries/{id}")
    @Operation(summary = "查询资源库详情")
    public Result<ResourceLibraryResponse> findLibrary(@PathVariable String id) {
        ResourceLibrary library = resourceLibraryService.findLibraryById(id);
        return Result.success(toLibraryResponse(library));
    }

    @PostMapping("/libraries")
    @Operation(summary = "创建资源库")
    @Log(module = LogModule.COURSE_RESOURCE, type = LogOperationType.CREATE, description = "创建资源库")
    @RequireRole(UserRole.ADMIN)
    public Result<ResourceLibraryResponse> createLibrary(@Valid @RequestBody ResourceLibraryCreateRequest request) {
        ResourceLibrary library = resourceLibraryService.createLibrary(
                request.getName(),
                request.getType(),
                request.getDescription(),
                request.getTenantId()
        );
        return Result.success(toLibraryResponse(library));
    }

    @PutMapping("/libraries/{id}")
    @Operation(summary = "更新资源库")
    @Log(module = LogModule.COURSE_RESOURCE, type = LogOperationType.UPDATE, description = "更新资源库")
    @RequireRole(UserRole.ADMIN)
    public Result<ResourceLibraryResponse> updateLibrary(
            @PathVariable String id,
            @Valid @RequestBody ResourceLibraryUpdateRequest request) {
        ResourceLibrary library = resourceLibraryService.updateLibrary(
                id,
                request.getName(),
                request.getDescription()
        );
        return Result.success(toLibraryResponse(library));
    }

    @DeleteMapping("/libraries/{id}")
    @Operation(summary = "删除资源库")
    @Log(module = LogModule.COURSE_RESOURCE, type = LogOperationType.DELETE, description = "删除资源库")
    @RequireRole(UserRole.ADMIN)
    public Result<Void> deleteLibrary(@PathVariable String id) {
        resourceLibraryService.deleteLibrary(id);
        return Result.success();
    }

    // ==================== 资源项目管理 ====================

    @GetMapping("/items")
    @Operation(summary = "分页查询资源项目")
    public Result<PageResult<ResourceItemResponse>> findAllItems(
            @RequestParam(required = false) String libraryId,
            @RequestParam(required = false) String fileType,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "20") Integer pageSize) {
        Page<ResourceItem> page = resourceLibraryService.findAllItems(libraryId, fileType, keyword, pageNum, pageSize);

        List<ResourceItemResponse> responses = page.getRecords().stream()
                .map(this::toItemResponse)
                .collect(Collectors.toList());

        return Result.success(PageResult.of(responses, page.getTotal(), page.getCurrent(), page.getSize()));
    }

    @GetMapping("/items/{id}")
    @Operation(summary = "查询资源项目详情")
    public Result<ResourceItemResponse> findItem(@PathVariable String id) {
        ResourceItem item = resourceLibraryService.findItemById(id);
        return Result.success(toItemResponse(item));
    }

    @PostMapping("/items")
    @Operation(summary = "创建资源项目")
    @Log(module = LogModule.COURSE_RESOURCE, type = LogOperationType.CREATE, description = "创建资源项目")
    @RequireRole(UserRole.ADMIN)
    public Result<ResourceItemResponse> createItem(@Valid @RequestBody ResourceItemCreateRequest request) throws JsonProcessingException {
        String tagsStr = null;
        if (request.getTags() != null && !request.getTags().isEmpty()) {
            tagsStr = objectMapper.writeValueAsString(request.getTags());
        }
        ResourceItem item = resourceLibraryService.createItem(
                request.getLibraryId(),
                request.getTitle(),
                request.getFileType(),
                request.getFilePath(),
                request.getFileSize(),
                request.getDescription(),
                tagsStr,
                request.getTenantId()
        );
        return Result.success(toItemResponse(item));
    }

    @PutMapping("/items/{id}")
    @Operation(summary = "更新资源项目")
    @Log(module = LogModule.COURSE_RESOURCE, type = LogOperationType.UPDATE, description = "更新资源项目")
    @RequireRole(UserRole.ADMIN)
    public Result<ResourceItemResponse> updateItem(
            @PathVariable String id,
            @Valid @RequestBody ResourceItemUpdateRequest request) throws JsonProcessingException {
        String tagsStr = null;
        if (request.getTags() != null && !request.getTags().isEmpty()) {
            tagsStr = objectMapper.writeValueAsString(request.getTags());
        }
        ResourceItem item = resourceLibraryService.updateItem(
                id,
                request.getTitle(),
                request.getDescription(),
                tagsStr
        );
        return Result.success(toItemResponse(item));
    }

    @DeleteMapping("/items/{id}")
    @Operation(summary = "删除资源项目")
    @Log(module = LogModule.COURSE_RESOURCE, type = LogOperationType.DELETE, description = "删除资源项目")
    @RequireRole(UserRole.ADMIN)
    public Result<Void> deleteItem(@PathVariable String id) {
        resourceLibraryService.deleteItem(id);
        return Result.success();
    }

    @PostMapping("/items/batch-delete")
    @Operation(summary = "批量删除资源项目")
    @Log(module = LogModule.COURSE_RESOURCE, type = LogOperationType.DELETE, description = "批量删除资源项目")
    @RequireRole(UserRole.ADMIN)
    public Result<Void> batchDeleteItems(@RequestBody List<String> ids) {
        resourceLibraryService.batchDeleteItems(ids);
        return Result.success();
    }

    // ==================== 统计数据 ====================

    @GetMapping("/stats")
    @Operation(summary = "获取统计数据")
    public Result<Map<String, Object>> getStats() {
        return Result.success(resourceLibraryService.getStats());
    }

    /**
     * 将 ResourceLibrary 实体转换为 ResourceLibraryResponse
     */
    private ResourceLibraryResponse toLibraryResponse(ResourceLibrary library) {
        return ResourceLibraryResponse.builder()
                .id(library.getId())
                .tenantId(library.getTenantId())
                .name(library.getName())
                .description(library.getDescription())
                .type(library.getLibraryType())
                .createdBy(library.getCreatedBy() != null ? String.valueOf(library.getCreatedBy()) : null)
                .createdAt(library.getCreatedAt())
                .updatedAt(library.getUpdatedAt())
                .build();
    }

    /**
     * 将 ResourceItem 实体转换为 ResourceItemResponse
     */
    private ResourceItemResponse toItemResponse(ResourceItem item) {
        ResourceItemResponse.LibrarySummary librarySummary = null;
        if (item.getLibraryId() != null && !item.getLibraryId().isEmpty()) {
            var lib = resourceLibraryService.findLibraryByIdOrNull(item.getLibraryId());
            if (lib != null) {
                librarySummary = ResourceItemResponse.LibrarySummary.builder()
                        .id(lib.getId())
                        .name(lib.getName())
                        .libraryType(lib.getLibraryType())
                        .build();
            }
        }

        List<String> tagsList = parseTagsJson(item.getTags());

        return ResourceItemResponse.builder()
                .id(item.getId())
                .libraryId(item.getLibraryId())
                .tenantId(item.getTenantId())
                .title(item.getTitle())
                .fileType(item.getFileType())
                .filePath(item.getFilePath())
                .fileSize(item.getFileSize())
                .tags(tagsList)
                .library(librarySummary)
                .description(item.getDescription())
                .status(item.getStatus())
                .createdAt(item.getCreatedAt())
                .updatedAt(item.getUpdatedAt())
                .build();
    }

    private List<String> parseTagsJson(String tagsJson) {
        if (tagsJson == null || tagsJson.isEmpty()) return List.of();
        try {
            return objectMapper.readValue(tagsJson, objectMapper.getTypeFactory().constructCollectionType(List.class, String.class));
        } catch (Exception e) {
            return List.of();
        }
    }
}