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.dto.ReplyRequest;
import com.gpf.pethospital.entity.Message;
import com.gpf.pethospital.security.AuthUser;
import com.gpf.pethospital.service.MessageService;
import com.gpf.pethospital.util.SecurityUtils;
import jakarta.validation.Valid;
// import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/messages")
public class MessageController {
    private final MessageService messageService;

    public MessageController(MessageService messageService) {
        this.messageService = messageService;
    }

    @PostMapping
    public ApiResponse<?> create(@RequestBody Message message) {
        AuthUser user = SecurityUtils.currentUser();
        if (user != null) {
            message.setUserId(user.getId());
            message.setUserName(user.getUsername());
        }
        message.setStatus("PENDING");
        messageService.save(message);
        return ApiResponse.success("created", null);
    }

    // @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin")
    public ApiResponse<?> list(@RequestParam(defaultValue = "1") long page,
                               @RequestParam(defaultValue = "10") long size,
                               @RequestParam(required = false) String status) {
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        if (status != null && !status.isBlank()) {
            wrapper.eq(Message::getStatus, status);
        }
        return ApiResponse.success(messageService.page(new Page<>(page, size), wrapper));
    }

    // @PreAuthorize("hasRole('ADMIN')")
    @PutMapping("/admin/{id}/reply")
    public ApiResponse<?> reply(@PathVariable Long id, @Valid @RequestBody ReplyRequest request) {
        AuthUser user = SecurityUtils.currentUser();
        Message update = new Message();
        update.setId(id);
        update.setReply(request.getReply());
        update.setStatus("PROCESSED");
        update.setReplyTime(LocalDateTime.now());
        if (user != null) {
            update.setReplyUserId(user.getId());
        }
        messageService.updateById(update);
        return ApiResponse.success("updated", null);
    }
}
