package com.dora.controller;

import com.dora.common.Result;
import com.dora.dto.PlazaWorkDto.*;
import com.dora.service.PlazaService;
import com.dora.util.SecurityUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 广场控制器
 * 
 * @author 1818AI
 * @since 2025-10-26
 */
@Slf4j
@RestController
@RequestMapping("/user/plaza")
@Tag(name = "广场功能", description = "用户端API - AI作品广场，发布、浏览、点赞作品")
@RequiredArgsConstructor
public class PlazaController {

    private final PlazaService plazaService;

    /**
     * 发布作品到广场
     */
    @PostMapping("/works/publish")
    @Operation(
        summary = "发布作品到广场", 
        description = "将已完成的AI任务作品发布到广场，供其他用户浏览。每个任务只能发布一次。"
    )
    public Result<WorkDetailResponse> publishWork(
            @Valid @RequestBody PublishWorkRequest request) {
        try {
            Long userId = SecurityUtil.getCurrentUserId();
            WorkDetailResponse response = plazaService.publishWork(userId, request);
            return Result.success(response);
        } catch (Exception e) {
            log.error("发布作品失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 查询广场作品列表
     */
    @GetMapping("/works/list")
    @Operation(
        summary = "查询广场作品列表", 
        description = "分页查询公开的广场作品，支持按任务类型筛选、按热度或时间排序。"
    )
    public Result<WorkListResponse> getPlazaWorks(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer page,
            
            @Parameter(description = "每页数量", example = "20")
            @RequestParam(defaultValue = "20") Integer size,
            
            @Parameter(description = "任务类型筛选", example = "text_to_image")
            @RequestParam(required = false) String taskType,
            
            @Parameter(description = "排序方式：latest-最新，hot-最热", example = "latest")
            @RequestParam(defaultValue = "latest") String sortBy) {
        
        try {
            Long userId = SecurityUtil.getCurrentUserIdOrNull();
            
            WorkQueryRequest request = WorkQueryRequest.builder()
                    .page(page)
                    .size(size)
                    .taskType(taskType)
                    .sortBy(sortBy)
                    .build();
            
            WorkListResponse response = plazaService.getPlazaWorks(userId, request);
            return Result.success(response);
        } catch (Exception e) {
            log.error("查询广场作品列表失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 查询作品详情
     */
    @GetMapping("/works/{workNo}")
    @Operation(
        summary = "查询作品详情", 
        description = "根据作品编号查询作品的详细信息，包括作者、点赞数、浏览数等。查看时会自动增加浏览数。支持通过queryType参数指定查询类型：workNo（默认）或taskId。"
    )
    public Result<WorkDetailResponse> getWorkDetail(
            @Parameter(description = "作品编号或任务编号", required = true)
            @PathVariable(name = "workNo", required = true) String workNo,
            
            @Parameter(description = "查询类型：workNo-作品编号（默认），taskId-任务编号", example = "workNo")
            @RequestParam(defaultValue = "workNo") String queryType) {
        
        try {
            Long userId = SecurityUtil.getCurrentUserIdOrNull();
            
            WorkDetailResponse response;
            
            // 根据查询类型处理
            if ("taskId".equalsIgnoreCase(queryType)) {
                // 通过taskId查询，不记录浏览
                log.info("通过taskId查询作品详情，taskNo: {}", workNo);
                response = plazaService.getWorkDetailByTaskNo(userId, workNo);
            } else {
                // 通过workNo查询，记录浏览
                log.info("通过workNo查询作品详情，workNo: {}", workNo);
                plazaService.recordView(workNo, userId);
                response = plazaService.getWorkDetail(userId, workNo);
            }
            
            return Result.success(response);
        } catch (Exception e) {
            log.error("查询作品详情失败，identifier: {}, queryType: {}", workNo, queryType, e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 点赞作品
     */
    @PostMapping("/works/{workNo}/like")
    @Operation(
        summary = "点赞作品", 
        description = "给喜欢的作品点赞，每个用户对每个作品只能点赞一次。"
    )
    public Result<LikeResponse> likeWork(
            @Parameter(description = "作品编号", required = true)
            @PathVariable(name = "workNo", required = true) String workNo) {
        
        try {
            Long userId = SecurityUtil.getCurrentUserId();
            LikeResponse response = plazaService.likeWork(userId, workNo);
            return Result.success(response);
        } catch (Exception e) {
            log.error("点赞作品失败，workNo: {}", workNo, e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 取消点赞
     */
    @DeleteMapping("/works/{workNo}/like")
    @Operation(
        summary = "取消点赞", 
        description = "取消对作品的点赞。"
    )
    public Result<LikeResponse> unlikeWork(
            @Parameter(description = "作品编号", required = true)
            @PathVariable(name = "workNo", required = true) String workNo) {
        
        try {
            Long userId = SecurityUtil.getCurrentUserId();
            LikeResponse response = plazaService.unlikeWork(userId, workNo);
            return Result.success(response);
        } catch (Exception e) {
            log.error("取消点赞失败，workNo: {}", workNo, e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 查询我的作品
     */
    @GetMapping("/my-works")
    @Operation(
        summary = "查询我的作品", 
        description = "查询当前用户发布到广场的所有作品，包括草稿、已发布、已隐藏的作品。"
    )
    public Result<WorkListResponse> getMyWorks(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer page,
            
            @Parameter(description = "每页数量", example = "10")
            @RequestParam(defaultValue = "10") Integer size,
            
            @Parameter(description = "状态筛选", example = "published")
            @RequestParam(required = false) String status) {
        
        try {
            Long userId = SecurityUtil.getCurrentUserId();
            
            WorkQueryRequest request = WorkQueryRequest.builder()
                    .page(page)
                    .size(size)
                    .status(status)
                    .build();
            
            WorkListResponse response = plazaService.getUserWorks(userId, request);
            return Result.success(response);
        } catch (Exception e) {
            log.error("查询我的作品失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除作品
     */
    @DeleteMapping("/works/{workNo}")
    @Operation(
        summary = "删除作品", 
        description = "删除自己发布的作品。删除后作品将不再在广场展示，且无法恢复。"
    )
    public Result<String> deleteWork(
            @Parameter(description = "作品编号", required = true)
            @PathVariable(name = "workNo", required = true) String workNo) {
        
        try {
            Long userId = SecurityUtil.getCurrentUserId();
            plazaService.deleteWork(userId, workNo);
            return Result.success("删除成功");
        } catch (Exception e) {
            log.error("删除作品失败，workNo: {}", workNo, e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取广场统计数据
     */
    @GetMapping("/stats")
    @Operation(
        summary = "获取广场统计数据", 
        description = "获取广场的总体统计数据，包括总作品数、总浏览数、总点赞数，以及各类型作品的数量分布。"
    )
    public Result<PlazaStatsResponse> getPlazaStats() {
        try {
            PlazaStatsResponse response = plazaService.getPlazaStats();
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取广场统计数据失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 查询我的点赞列表
     */
    @GetMapping("/my-likes")
    @Operation(
        summary = "查询我的点赞列表", 
        description = "查询当前用户点赞过的作品列表，按点赞时间倒序排列。"
    )
    public Result<UserLikedWorksResponse> getMyLikedWorks(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer page,
            
            @Parameter(description = "每页数量", example = "10")
            @RequestParam(defaultValue = "10") Integer size) {
        
        try {
            Long userId = SecurityUtil.getCurrentUserId();
            UserLikedWorksResponse response = plazaService.getUserLikedWorks(userId, page, size);
            return Result.success(response);
        } catch (Exception e) {
            log.error("查询我的点赞列表失败", e);
            return Result.error(e.getMessage());
        }
    }
}

