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.Pet;
import com.gpf.pethospital.entity.VaccineRecord;
import com.gpf.pethospital.security.AuthUser;
import com.gpf.pethospital.service.PetService;
import com.gpf.pethospital.service.VaccineRecordService;
import com.gpf.pethospital.util.SecurityUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/vaccines")
public class VaccineRecordController {
    private final VaccineRecordService vaccineRecordService;
    private final PetService petService;

    public VaccineRecordController(VaccineRecordService vaccineRecordService, PetService petService) {
        this.vaccineRecordService = vaccineRecordService;
        this.petService = petService;
    }

    @GetMapping
    public ApiResponse<?> list(@RequestParam Long petId,
                               @RequestParam(defaultValue = "1") long page,
                               @RequestParam(defaultValue = "10") long size) {
        AuthUser user = SecurityUtils.currentUser();
        if (user != null && "CUSTOMER".equals(user.getRole())) {
            Pet pet = petService.getById(petId);
            if (pet == null || !pet.getOwnerId().equals(user.getId())) {
                return ApiResponse.error(403, "forbidden");
            }
        }
        LambdaQueryWrapper<VaccineRecord> wrapper = new LambdaQueryWrapper<VaccineRecord>()
                .eq(VaccineRecord::getPetId, petId);
        return ApiResponse.success(vaccineRecordService.page(new Page<>(page, size), wrapper));
    }

    @PostMapping
    public ApiResponse<?> create(@RequestBody VaccineRecord record) {
        vaccineRecordService.save(record);
        return ApiResponse.success("created", null);
    }

    @PutMapping("/{id}")
    public ApiResponse<?> update(@PathVariable Long id, @RequestBody VaccineRecord record) {
        record.setId(id);
        vaccineRecordService.updateById(record);
        return ApiResponse.success("updated", null);
    }

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