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.Report;
import com.gpf.pethospital.security.AuthUser;
import com.gpf.pethospital.service.ReportService;
import com.gpf.pethospital.util.SecurityUtils;
// import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/reports")
public class ReportController {
    private final ReportService reportService;

    public ReportController(ReportService reportService) {
        this.reportService = reportService;
    }

    // @PreAuthorize("hasAnyRole('ADMIN','DOCTOR')")
    @PostMapping
    public ApiResponse<?> create(@RequestBody Report report) {
        AuthUser user = SecurityUtils.currentUser();
        if (user != null) {
            report.setDoctorId(user.getId());
        }
        reportService.save(report);
        return ApiResponse.success("created", null);
    }

    @GetMapping
    public ApiResponse<?> list(@RequestParam(defaultValue = "1") long page,
                               @RequestParam(defaultValue = "10") long size,
                               @RequestParam(required = false) Long petId) {
        AuthUser user = SecurityUtils.currentUser();
        LambdaQueryWrapper<Report> wrapper = new LambdaQueryWrapper<>();
        if (petId != null) {
            wrapper.eq(Report::getPetId, petId);
        }
        if (user != null && "DOCTOR".equals(user.getRole())) {
            wrapper.eq(Report::getDoctorId, user.getId());
        }
        return ApiResponse.success(reportService.page(new Page<>(page, size), wrapper));
    }

    // @PreAuthorize("hasAnyRole('ADMIN','DOCTOR')")
    @PutMapping("/{id}")
    public ApiResponse<?> update(@PathVariable Long id, @RequestBody Report report) {
        report.setId(id);
        reportService.updateById(report);
        return ApiResponse.success("updated", null);
    }

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