package com.nanri.aiimage.modules.shopkey.controller;

import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageCreateRequest;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageUpdateRequest;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupCreateRequest;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupUpdateRequest;
import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageItemVo;
import com.nanri.aiimage.modules.shopkey.model.vo.ShopManagePageVo;
import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageGroupItemVo;
import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageCredentialVo;
import com.nanri.aiimage.modules.shopkey.service.ShopManageService;
import com.nanri.aiimage.modules.shopkey.service.ShopManageGroupService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/admin/shop-manages")
@Tag(name = "店铺管理", description = "维护店铺信息，支持增删改查。")
public class ShopManageController {

    @Value("${aiimage.security.internal-token:}")
    private String internalToken;

    private final ShopManageService shopManageService;
    private final ShopManageGroupService shopManageGroupService;

    @GetMapping
    @Operation(summary = "分页查询店铺", description = "分页查询店铺列表。")
    @ApiResponses({
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = ShopManagePageVo.class)))
    })
    public ApiResponse<ShopManagePageVo> page(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize) {
        return ApiResponse.success(shopManageService.page(page, pageSize));
    }

    @PostMapping
    @Operation(summary = "新增店铺", description = "新增一条店铺记录。")
    public ApiResponse<ShopManageItemVo> create(@Valid @RequestBody ShopManageCreateRequest request) {
        return ApiResponse.success("创建成功", shopManageService.create(request));
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新店铺", description = "按 ID 更新一条店铺记录。")
    public ApiResponse<ShopManageItemVo> update(
            @Parameter(description = "主键ID", required = true) @PathVariable Long id,
            @Valid @RequestBody ShopManageUpdateRequest request) {
        return ApiResponse.success("更新成功", shopManageService.update(id, request));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除店铺", description = "按 ID 删除一条店铺记录。")
    public ApiResponse<Void> delete(@Parameter(description = "主键ID", required = true) @PathVariable Long id) {
        shopManageService.delete(id);
        return ApiResponse.success("删除成功", null);
    }

    @GetMapping("/groups")
    @Operation(summary = "查询分组列表", description = "用于店铺管理下拉选择。")
    public ApiResponse<java.util.List<ShopManageGroupItemVo>> listGroups() {
        return ApiResponse.success(shopManageGroupService.list());
    }

    @PostMapping("/groups")
    @Operation(summary = "新增分组", description = "新增一条店铺分组。")
    public ApiResponse<ShopManageGroupItemVo> createGroup(@Valid @RequestBody ShopManageGroupCreateRequest request) {
        return ApiResponse.success("创建成功", shopManageGroupService.create(request));
    }

    @PutMapping("/groups/{id}")
    @Operation(summary = "更新分组", description = "按 ID 更新分组名称。")
    public ApiResponse<ShopManageGroupItemVo> updateGroup(
            @Parameter(description = "主键ID", required = true) @PathVariable Long id,
            @Valid @RequestBody ShopManageGroupUpdateRequest request) {
        return ApiResponse.success("更新成功", shopManageGroupService.update(id, request));
    }

    @DeleteMapping("/groups/{id}")
    @Operation(summary = "删除分组", description = "删除分组（分组下有店铺时不允许删除）。")
    public ApiResponse<Void> deleteGroup(@Parameter(description = "主键ID", required = true) @PathVariable Long id) {
        shopManageGroupService.delete(id);
        return ApiResponse.success("删除成功", null);
    }

    @GetMapping("/credential")
    @Operation(summary = "按店铺名获取明文凭据（内部）", description = "仅供 Python 自动化内部调用，需传 X-Internal-Token。")
    public ApiResponse<ShopManageCredentialVo> getCredentialByShopName(
            @RequestParam("shopName") String shopName,
            @RequestHeader(value = "X-Internal-Token", required = false) String token) {
        if (internalToken == null || internalToken.isBlank() || token == null || !internalToken.equals(token)) {
            throw new com.nanri.aiimage.common.exception.BusinessException("无权访问凭据");
        }
        return ApiResponse.success(shopManageService.getCredentialByShopName(shopName));
    }
}
