package shop.alien.store.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.store.dto.ShortLinkResolveResponse;
import shop.alien.store.dto.ShortLinkShortenRequest;
import shop.alien.store.dto.ShortLinkShortenResponse;
import shop.alien.store.service.ShortLinkService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 短链接：前端生成短链、解析长链（JSON）；可选 open 路径 302。
 */
@Api(tags = {"短链接"})
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/store/short-link")
@RequiredArgsConstructor
public class ShortLinkController {

    private final ShortLinkService shortLinkService;

    @ApiOperation(value = "生成短链", notes = "需在配置 short-link.public-base-url 后返回完整 https 短 URL。可选 short-link.allowed-hosts 限制长链域名。")
    @PostMapping("/shorten")
    public R<ShortLinkShortenResponse> shorten(@RequestBody ShortLinkShortenRequest request) {
        if (request == null || !StringUtils.hasText(request.getLongUrl())) {
            return R.fail("longUrl 不能为空");
        }
        try {
            ShortLinkShortenResponse res = shortLinkService.shorten(request.getLongUrl());
            return R.data(res);
        } catch (IllegalArgumentException ex) {
            return R.fail(ex.getMessage());
        } catch (Exception ex) {
            log.warn("生成短链失败: {}", ex.getMessage());
            return R.fail("生成短链失败");
        }
    }

    @ApiOperation(value = "解析短链", notes = "返回原始 longUrl，由前端自行跳转；无需登录")
    @GetMapping("/s/{code}")
    public R<ShortLinkResolveResponse> resolve(@PathVariable String code) {
        String longUrl = shortLinkService.resolveLongUrl(code);
        if (!StringUtils.hasText(longUrl)) {
            return R.fail("链接不存在或已过期");
        }
        return R.data(new ShortLinkResolveResponse(longUrl));
    }

    @ApiOperation(value = "短链浏览器跳转", notes = "302 到原始长链接；无需登录（书签/H5 直开用，小程序一般用上方 JSON 接口）")
    @GetMapping("/s/{code}/open")
    public void openRedirect(@PathVariable String code, HttpServletResponse response) throws IOException {
        String longUrl = shortLinkService.resolveLongUrl(code);
        if (!StringUtils.hasText(longUrl)) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "链接不存在或已过期");
            return;
        }
        response.sendRedirect(longUrl);
    }
}
