package com.competition.modules.pub.controller;

import com.competition.common.result.PageResult;
import com.competition.common.result.Result;
import com.competition.common.util.SecurityUtil;
import com.competition.modules.pub.service.PublicInteractionService;
import com.competition.modules.pub.service.PublicUserWorkService;
import com.competition.modules.ugc.entity.UgcWork;
import com.competition.modules.ugc.entity.UgcWorkPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Tag(name = "作品库")
@RestController
@RequestMapping("/public/works")
@RequiredArgsConstructor
public class PublicUserWorkController {

    private final PublicUserWorkService publicUserWorkService;
    private final PublicInteractionService publicInteractionService;

    @PostMapping
    @Operation(summary = "创建作品")
    public Result<UgcWork> create(@RequestBody Map<String, Object> body) {
        Long userId = SecurityUtil.getCurrentUserId();
        String title = (String) body.get("title");
        String coverUrl = (String) body.get("coverUrl");
        String description = (String) body.get("description");
        String visibility = (String) body.get("visibility");
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> pages = (List<Map<String, Object>>) body.get("pages");
        @SuppressWarnings("unchecked")
        List<Long> tagIds = body.get("tagIds") != null
                ? ((List<Number>) body.get("tagIds")).stream().map(Number::longValue).toList()
                : null;
        return Result.success(publicUserWorkService.create(userId, title, coverUrl, description, visibility, pages, tagIds));
    }

    @GetMapping
    @Operation(summary = "我的作品列表")
    public Result<PageResult<UgcWork>> list(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String keyword) {
        Long userId = SecurityUtil.getCurrentUserId();
        return Result.success(publicUserWorkService.findMyWorks(userId, page, pageSize, status, keyword));
    }

    @GetMapping("/{id}")
    @Operation(summary = "作品详情")
    public Result<Map<String, Object>> detail(@PathVariable Long id) {
        Long userId = SecurityUtil.getCurrentUserId();
        return Result.success(publicUserWorkService.findDetail(id, userId));
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新作品")
    public Result<Void> update(@PathVariable Long id, @RequestBody Map<String, Object> body) {
        Long userId = SecurityUtil.getCurrentUserId();
        publicUserWorkService.update(id, userId, body);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除作品")
    public Result<Void> delete(@PathVariable Long id) {
        Long userId = SecurityUtil.getCurrentUserId();
        publicUserWorkService.delete(id, userId);
        return Result.success();
    }

    @PostMapping("/{id}/publish")
    @Operation(summary = "发布作品（提交审核）")
    public Result<Void> publish(@PathVariable Long id) {
        Long userId = SecurityUtil.getCurrentUserId();
        publicUserWorkService.publish(id, userId);
        return Result.success();
    }

    @GetMapping("/{id}/pages")
    @Operation(summary = "获取作品页面")
    public Result<List<UgcWorkPage>> getPages(@PathVariable Long id) {
        return Result.success(publicUserWorkService.getPages(id));
    }

    @PostMapping("/{id}/pages")
    @Operation(summary = "保存作品页面")
    public Result<Void> savePages(@PathVariable Long id, @RequestBody Map<String, Object> body) {
        Long userId = SecurityUtil.getCurrentUserId();
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> pages = (List<Map<String, Object>>) body.get("pages");
        publicUserWorkService.savePages(id, userId, pages);
        return Result.success();
    }

    @PostMapping("/batch-interaction")
    @Operation(summary = "批量获取互动状态")
    public Result<Map<Long, Map<String, Object>>> batchInteraction(@RequestBody Map<String, Object> body) {
        Long userId = SecurityUtil.getCurrentUserId();
        @SuppressWarnings("unchecked")
        List<Long> workIds = body.get("workIds") != null
                ? ((List<Number>) body.get("workIds")).stream().map(Number::longValue).toList()
                : List.of();
        return Result.success(publicInteractionService.batchGetInteractionStatus(workIds, userId));
    }

    @PostMapping("/{id}/like")
    @Operation(summary = "点赞/取消点赞")
    public Result<Map<String, Object>> toggleLike(@PathVariable Long id) {
        Long userId = SecurityUtil.getCurrentUserId();
        return Result.success(publicInteractionService.toggleLike(id, userId));
    }

    @PostMapping("/{id}/favorite")
    @Operation(summary = "收藏/取消收藏")
    public Result<Map<String, Object>> toggleFavorite(@PathVariable Long id) {
        Long userId = SecurityUtil.getCurrentUserId();
        return Result.success(publicInteractionService.toggleFavorite(id, userId));
    }

    @GetMapping("/{id}/interaction")
    @Operation(summary = "获取互动状态")
    public Result<Map<String, Object>> getInteraction(@PathVariable Long id) {
        Long userId = SecurityUtil.getCurrentUserId();
        return Result.success(publicInteractionService.getInteractionStatus(id, userId));
    }
}
