package com.kym.miniapp.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.kym.common.R;
import com.kym.service.CarsService;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/cars")
public class CarsController {

    private final CarsService carsService;

    public CarsController(CarsService carsService) {
        this.carsService = carsService;
    }

    @GetMapping("/list")
    public R<?> list() {
        var userId = StpUtil.getLoginIdAsLong();
        return R.success(carsService.listUserCars(userId));
    }

    @PostMapping("/save")
    public R<?> save(@RequestBody Map<String, String> body) {
        var userId = StpUtil.getLoginIdAsLong();
        var plateNo = body.get("plateNo");
        boolean isNew = carsService.saveCar(userId, plateNo);
        return R.success(Map.of("isNew", isNew));
    }

    @PostMapping("/setDefault/{id}")
    public R<?> setDefault(@PathVariable String id) {
        var userId = StpUtil.getLoginIdAsLong();
        carsService.setDefault(userId, Long.parseLong(id));
        return R.success();
    }

    @PostMapping("/delete/{id}")
    public R<?> delete(@PathVariable String id) {
        var userId = StpUtil.getLoginIdAsLong();
        carsService.deleteCar(userId, Long.parseLong(id));
        return R.success();
    }
}
