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

@RestController
@RequestMapping("/prescriptions")
public class PrescriptionController {
    private final PrescriptionService prescriptionService;

    public PrescriptionController(PrescriptionService prescriptionService) {
        this.prescriptionService = prescriptionService;
    }

    // @PreAuthorize("hasAnyRole('ADMIN','DOCTOR')")
    @PostMapping
    public ApiResponse<?> create(@RequestBody Prescription prescription) {
        if (prescription.getStatus() == null) {
            prescription.setStatus("DRAFT");
        }
        prescriptionService.save(prescription);
        return ApiResponse.success("created", null);
    }

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

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