package com.usky.vpp.controller.web;

import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.bean.CommonPage;
import com.usky.vpp.service.VppBiddingConfigService;
import com.usky.vpp.service.vo.BiddingConfigRequest;
import com.usky.vpp.service.vo.BiddingConfigVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 竞价配置接口
 * 网关前缀: /prod-api/service-vpp/bidding
 */
@RestController
@RequestMapping("/bidding")
public class BiddingConfigController {

    private static final DateTimeFormatter DATE_TIME_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private VppBiddingConfigService biddingConfigService;

    /**
     * 分页查询竞价配置
     */
    @GetMapping("/config")
    public ApiResult<CommonPage<BiddingConfigVO>> page(
            @RequestParam(value = "configName", required = false) String configName,
            @RequestParam(value = "effectiveStart", required = false) String effectiveStart,
            @RequestParam(value = "effectiveEnd", required = false) String effectiveEnd,
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "size", required = false, defaultValue = "20") Integer size) {
        return ApiResult.success(biddingConfigService.page(
                configName,
                parseDateTime(effectiveStart),
                parseDateTime(effectiveEnd),
                current,
                size));
    }

    /**
     * 竞价配置详情
     */
    @GetMapping("/config/{id}")
    public ApiResult<BiddingConfigVO> get(@PathVariable("id") Long id) {
        return ApiResult.success(biddingConfigService.get(id));
    }

    /**
     * 新增竞价配置
     */
    @PostMapping("/config")
    public ApiResult<Long> create(@RequestBody BiddingConfigRequest body) {
        return ApiResult.success(biddingConfigService.create(body));
    }

    /**
     * 更新竞价配置
     */
    @PutMapping("/config/{id}")
    public ApiResult<Void> update(@PathVariable("id") Long id, @RequestBody BiddingConfigRequest body) {
        biddingConfigService.update(id, body);
        return ApiResult.success();
    }

    /**
     * 删除竞价配置（软删除）
     */
    @DeleteMapping("/config/{id}")
    public ApiResult<Void> delete(@PathVariable("id") Long id) {
        biddingConfigService.delete(id);
        return ApiResult.success();
    }

    private LocalDateTime parseDateTime(String value) {
        if (!org.springframework.util.StringUtils.hasText(value)) {
            return null;
        }
        return LocalDateTime.parse(value.trim(), DATE_TIME_FMT);
    }
}
