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

@RestController
@RequestMapping("/visits")
public class VisitController {
    private final VisitService visitService;

    public VisitController(VisitService visitService) {
        this.visitService = visitService;
    }

    // @PreAuthorize("hasAnyRole('ADMIN','DOCTOR')")
    @PostMapping
    public ApiResponse<?> create(@RequestBody Visit visit) {
        if (visit.getStatus() == null) {
            visit.setStatus("IN_PROGRESS");
        }
        if (visit.getPaymentStatus() == null) {
            visit.setPaymentStatus("UNPAID");
        }
        visitService.save(visit);
        return ApiResponse.success("created", null);
    }

    @GetMapping
    public ApiResponse<?> list(@RequestParam(defaultValue = "1") long page,
                               @RequestParam(defaultValue = "10") long size) {
        AuthUser user = SecurityUtils.currentUser();
        LambdaQueryWrapper<Visit> wrapper = new LambdaQueryWrapper<>();
        if (user != null) {
            if ("CUSTOMER".equals(user.getRole())) {
                wrapper.eq(Visit::getCustomerId, user.getId());
            } else if ("DOCTOR".equals(user.getRole())) {
                wrapper.eq(Visit::getDoctorId, user.getId());
            }
        }
        return ApiResponse.success(visitService.page(new Page<>(page, size), wrapper));
    }

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