package com.gpf.pethospital.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gpf.pethospital.common.ApiResponse;
import com.gpf.pethospital.entity.Notice;
import com.gpf.pethospital.security.AuthUser;
import com.gpf.pethospital.service.NoticeService;
import com.gpf.pethospital.util.SecurityUtils;
// import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping
public class NoticeController {
    private final NoticeService noticeService;

    public NoticeController(NoticeService noticeService) {
        this.noticeService = noticeService;
    }

    @GetMapping("/public/notices")
    public ApiResponse<?> publicList(@RequestParam(defaultValue = "1") long page,
                                     @RequestParam(defaultValue = "10") long size) {
        LambdaQueryWrapper<Notice> wrapper = new LambdaQueryWrapper<Notice>()
                .eq(Notice::getStatus, 1)
                .orderByDesc(Notice::getIsTop)
                .orderByDesc(Notice::getCreateTime);
        return ApiResponse.success(noticeService.page(new Page<>(page, size), wrapper));
    }

    @GetMapping("/public/notices/{id}")
    public ApiResponse<?> publicDetail(@PathVariable Long id) {
        return ApiResponse.success(noticeService.getById(id));
    }

    // @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/notices")
    public ApiResponse<?> list(@RequestParam(defaultValue = "1") long page,
                               @RequestParam(defaultValue = "10") long size) {
        return ApiResponse.success(noticeService.page(new Page<>(page, size)));
    }

    // @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/notices")
    public ApiResponse<?> create(@RequestBody Notice notice) {
        if (notice.getPublisherId() == null) {
            AuthUser user = SecurityUtils.currentUser();
            if (user != null) {
                notice.setPublisherId(user.getId());
            }
        }
        if (notice.getPublisherId() == null) {
            return ApiResponse.error(400, "publisherId required");
        }
        if (notice.getStatus() == null) {
            notice.setStatus(1);
        }
        noticeService.save(notice);
        return ApiResponse.success("created", null);
    }

    // @PreAuthorize("hasRole('ADMIN')")
    @PutMapping("/notices/{id}")
    public ApiResponse<?> update(@PathVariable Long id, @RequestBody Notice notice) {
        notice.setId(id);
        noticeService.updateById(notice);
        return ApiResponse.success("updated", null);
    }

    // @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/notices/{id}")
    public ApiResponse<?> delete(@PathVariable Long id) {
        noticeService.removeById(id);
        return ApiResponse.success("deleted", null);
    }
}
