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.Drug;
import com.gpf.pethospital.entity.StockOut;
import com.gpf.pethospital.service.DrugService;
import com.gpf.pethospital.service.StockOutService;
// import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/stock-out")
public class StockOutController {
    private final StockOutService stockOutService;
    private final DrugService drugService;

    public StockOutController(StockOutService stockOutService, DrugService drugService) {
        this.stockOutService = stockOutService;
        this.drugService = drugService;
    }

    // @PreAuthorize("hasRole('ADMIN')")
    @GetMapping
    public ApiResponse<?> list(@RequestParam(defaultValue = "1") long page,
                               @RequestParam(defaultValue = "10") long size,
                               @RequestParam(required = false) Long drugId) {
        LambdaQueryWrapper<StockOut> wrapper = new LambdaQueryWrapper<>();
        if (drugId != null) {
            wrapper.eq(StockOut::getDrugId, drugId);
        }
        return ApiResponse.success(stockOutService.page(new Page<>(page, size), wrapper));
    }

    // @PreAuthorize("hasRole('ADMIN')")
    @PostMapping
    @Transactional
    public ApiResponse<?> create(@RequestBody StockOut stockOut) {
        stockOutService.save(stockOut);
        if (stockOut.getDrugId() != null && stockOut.getQuantity() != null) {
            Drug drug = drugService.getById(stockOut.getDrugId());
            if (drug != null) {
                int current = drug.getStock() == null ? 0 : drug.getStock();
                drug.setStock(Math.max(0, current - stockOut.getQuantity()));
                drugService.updateById(drug);
            }
        }
        return ApiResponse.success("created", null);
    }
}
