package com.izouma.nineth.web.mobile.v1;


import com.izouma.nineth.domain.UserAddress;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.UserAddressRepo;
import com.izouma.nineth.service.UserAddressService;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.SecurityUtils;
import com.izouma.nineth.web.BaseController;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/userAddress")
@AllArgsConstructor
public class UserAddressControllerV1 extends BaseController {
    private UserAddressService userAddressService;
    private UserAddressRepo    userAddressRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public UserAddress save(@RequestBody UserAddress record) {
        record.setUserId(currentUser().getId());
        if (record.getId() != null) {
            UserAddress orig = userAddressRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            if (orig.isDef()) {
                userAddressRepo.unsetDefault(SecurityUtils.getAuthenticatedUser().getId());
            }
            return userAddressRepo.save(orig);
        }
        if (record.isDef()) {
            userAddressRepo.unsetDefault(SecurityUtils.getAuthenticatedUser().getId());
        }
        return userAddressRepo.save(record);
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<UserAddress> all(@RequestBody PageQuery pageQuery) {
        return userAddressService.all(pageQuery);
    }

    @GetMapping("/get/{id}")
    public UserAddress get(@PathVariable Long id) {
        return userAddressRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }


}

