package com.lesingle.creation.controller;

import com.lesingle.creation.common.core.Result;
import com.lesingle.creation.common.security.UserPrincipal;
import com.lesingle.creation.dto.notice.CreateNoticeDTO;
import com.lesingle.creation.dto.notice.UpdateNoticeDTO;
import com.lesingle.creation.service.ContestNoticeService;
import com.lesingle.creation.vo.notice.NoticeVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 竞赛公告管理控制器
 */
@Tag(name = "竞赛公告管理")
@RestController
@RequestMapping("/api/contests/notices")
@RequiredArgsConstructor
public class ContestNoticeController {

    private final ContestNoticeService noticeService;

    @PostMapping
    @Operation(summary = "创建公告")
    @PreAuthorize("hasAuthority('contest:notice:create')")
    public Result<NoticeVO> create(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @RequestBody @Validated CreateNoticeDTO dto) {
        Long tenantId = userPrincipal.getTenantId();
        Long creatorId = userPrincipal.getUserId();
        NoticeVO result = noticeService.create(dto, creatorId);
        return Result.success(result);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新公告")
    @PreAuthorize("hasAuthority('contest:notice:update')")
    public Result<NoticeVO> update(
            @PathVariable Long id,
            @RequestBody @Validated UpdateNoticeDTO dto) {
        NoticeVO result = noticeService.update(id, dto);
        return Result.success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除公告")
    @PreAuthorize("hasAuthority('contest:notice:delete')")
    public Result<Void> delete(@PathVariable Long id) {
        noticeService.delete(id);
        return Result.success(null);
    }

    @PostMapping("/{id}/publish")
    @Operation(summary = "发布公告")
    @PreAuthorize("hasAuthority('contest:notice:publish')")
    public Result<NoticeVO> publish(@PathVariable Long id) {
        NoticeVO result = noticeService.publish(id);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取公告详情")
    @PreAuthorize("hasAuthority('contest:read')")
    public Result<NoticeVO> getDetail(@PathVariable Long id) {
        NoticeVO result = noticeService.getDetail(id);
        return Result.success(result);
    }

    @GetMapping("/contest/{contestId}")
    @Operation(summary = "查询活动的公告列表")
    @PreAuthorize("hasAuthority('contest:read')")
    public Result<List<NoticeVO>> listByContest(@PathVariable Long contestId) {
        List<NoticeVO> result = noticeService.listByContest(contestId);
        return Result.success(result);
    }
}
