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

@RestController
@RequestMapping("/stock-in")
public class StockInController {
    private final StockInService stockInService;
    private final DrugService drugService;

    public StockInController(StockInService stockInService, DrugService drugService) {
        this.stockInService = stockInService;
        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<StockIn> wrapper = new LambdaQueryWrapper<>();
        if (drugId != null) {
            wrapper.eq(StockIn::getDrugId, drugId);
        }
        return ApiResponse.success(stockInService.page(new Page<>(page, size), wrapper));
    }

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