package cn.reghao.devops.mgr.build.controller;

import cn.reghao.devops.common.docker.model.DockerAuth;
import cn.reghao.devops.mgr.build.db.repository.DockerRegistryRepository;
import cn.reghao.devops.mgr.build.model.po.DockerRegistry;
import cn.reghao.devops.mgr.build.service.DockerRegistryService;
import cn.reghao.devops.mgr.util.PageSort;
import cn.reghao.jutil.web.WebResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author reghao
 * @date 2024-07-26 17:36:37
 */
@Api(tags = "DockerRegistry 配置页面")
@Controller
@RequestMapping("/build")
public class DockerRegistryPageController {
    private final DockerRegistryRepository dockerRegistryRepository;
    private final DockerRegistryService dockerRegistryService;

    public DockerRegistryPageController(DockerRegistryRepository dockerRegistryRepository,
                                        DockerRegistryService dockerRegistryService) {
        this.dockerRegistryRepository = dockerRegistryRepository;
        this.dockerRegistryService = dockerRegistryService;
    }

    @ApiOperation(value = "DockerRegistry 列表页面", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/registry")
    public String repoAuthPage(Model model) {
        PageRequest pageRequest = PageSort.pageRequest();
        Page<DockerRegistry> page = dockerRegistryRepository.findAll(pageRequest);

        model.addAttribute("page", page);
        model.addAttribute("list", page.getContent());
        return "/devops/build/docker/index";
    }

    @ApiOperation(value = "DockerRegistry 添加页面", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/registry/add")
    public String addRepoAuthPage(Model model) {
        return "/devops/build/docker/add";
    }

    @ApiOperation(value = "添加 DockerRegistry 配置", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @PostMapping(value = "/registry", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String addOrUpdateRepoConfig(@Validated DockerAuth dockerAuth) {
        dockerRegistryService.addOrUpdate(dockerAuth);
        return WebResult.success();
    }

    @ApiOperation(value = "删除 DockerRegistry 配置", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @DeleteMapping(value = "/registry/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String deleteRepoConfig(@PathVariable("id") Integer id) {
        dockerRegistryService.delete(id);
        return WebResult.success();
    }
}
