package com.gxwebsoft.app.controller;

import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.app.service.AppVersionService;
import com.gxwebsoft.app.entity.AppVersion;
import com.gxwebsoft.app.param.AppVersionParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 应用版本发布记录控制器
 *
 * @author 科技小王子
 * @since 2026-03-28 21:29:44
 */
@Slf4j
@Tag(name = "应用版本发布管理")
@RestController
@RequestMapping("/api/app/app-version")
public class AppVersionController extends BaseController {

    @Resource
    private AppVersionService appVersionService;

    @Operation(summary = "分页查询版本记录")
    @GetMapping("/page")
    public ApiResult<PageResult<AppVersion>> page(AppVersionParam param) {
        return success(appVersionService.pageRel(param));
    }

    @Operation(summary = "查询全部版本记录")
    @GetMapping()
    public ApiResult<List<AppVersion>> list(AppVersionParam param) {
        return success(appVersionService.listRel(param));
    }

    @Operation(summary = "根据id查询版本")
    @GetMapping("/{id}")
    public ApiResult<AppVersion> get(@PathVariable("id") Integer id) {
        return success(appVersionService.getByIdRel(id));
    }

    @Operation(summary = "获取应用当前版本")
    @GetMapping("/current/{websiteId}")
    public ApiResult<AppVersion> getCurrentVersion(@PathVariable("websiteId") Long websiteId) {
        return success(appVersionService.getCurrentVersion(websiteId));
    }

    @PreAuthorize("hasAuthority('app:appVersion:save')")
    @OperationLog
    @Operation(summary = "新增版本（构建中状态）")
    @PostMapping()
    public ApiResult<?> save(@RequestBody AppVersion appVersion) {
        User loginUser = getLoginUser();
        if (loginUser != null) {
            appVersion.setUserId(loginUser.getUserId());
            appVersion.setTenantId(loginUser.getTenantId());
        }
        // 默认为构建中状态
        if (appVersion.getStatus() == null) {
            appVersion.setStatus(0);
        }
        if (appVersion.getEnv() == null) {
            appVersion.setEnv("production");
        }
        appVersion.setIsCurrent(false);
        if (appVersionService.save(appVersion)) {
            return success("创建成功");
        }
        return fail("创建失败");
    }

    @PreAuthorize("hasAuthority('app:appVersion:update')")
    @OperationLog
    @Operation(summary = "修改版本信息")
    @PutMapping()
    public ApiResult<?> update(@RequestBody AppVersion appVersion) {
        if (appVersionService.updateById(appVersion)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('app:appVersion:update')")
    @OperationLog
    @Operation(summary = "发布版本（将此版本设为当前运行版本）")
    @PostMapping("/publish/{id}")
    public ApiResult<?> publish(@PathVariable("id") Long id) {
        User loginUser = getLoginUser();
        if (loginUser == null) {
            return fail("请先登录");
        }
        try {
            appVersionService.publish(id, loginUser.getUserId());
            return success("发布成功");
        } catch (RuntimeException e) {
            return fail(e.getMessage());
        }
    }

    @PreAuthorize("hasAuthority('app:appVersion:update')")
    @OperationLog
    @Operation(summary = "回滚到指定版本")
    @PostMapping("/rollback/{id}")
    public ApiResult<?> rollback(@PathVariable("id") Long id) {
        User loginUser = getLoginUser();
        if (loginUser == null) {
            return fail("请先登录");
        }
        try {
            appVersionService.rollback(id, loginUser.getUserId());
            return success("回滚成功");
        } catch (RuntimeException e) {
            return fail(e.getMessage());
        }
    }

    @PreAuthorize("hasAuthority('app:appVersion:remove')")
    @OperationLog
    @Operation(summary = "删除版本记录")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (appVersionService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('app:appVersion:save')")
    @OperationLog
    @Operation(summary = "批量添加版本")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<AppVersion> list) {
        if (appVersionService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('app:appVersion:update')")
    @OperationLog
    @Operation(summary = "批量修改版本")
    @PutMapping("/batch")
    public ApiResult<?> updateBatch(@RequestBody BatchParam<AppVersion> batchParam) {
        if (batchParam.update(appVersionService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('app:appVersion:remove')")
    @OperationLog
    @Operation(summary = "批量删除版本记录")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (appVersionService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
