package handler

import (
	"kra/internal/service"
	"kra/internal/service/dto"

	"github.com/gin-gonic/gin"
)

type IntegrationConfig struct {
	service *service.IntegrationConfigService
}

func NewIntegrationConfig(service *service.IntegrationConfigService) *IntegrationConfig {
	return &IntegrationConfig{service: service}
}

func (h *IntegrationConfig) List(c *gin.Context) {
	configs, err := h.service.List(c.Request.Context(), c.Param("kind"))
	if err != nil {
		Fail(c, err.Error())
		return
	}
	OKWithData(c, configs)
}

func (h *IntegrationConfig) Find(c *gin.Context) {
	config, err := h.service.Find(c.Request.Context(), c.Param("kind"), c.Param("provider"))
	if err != nil {
		Fail(c, err.Error())
		return
	}
	OKWithData(c, config)
}

func (h *IntegrationConfig) Save(c *gin.Context) {
	var req dto.IntegrationConfigRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		Fail(c, err.Error())
		return
	}
	if err := h.service.Save(c.Request.Context(), c.Param("kind"), c.Param("provider"), &req); err != nil {
		Fail(c, err.Error())
		return
	}
	OK(c)
}

func (h *IntegrationConfig) Test(c *gin.Context) {
	var req dto.IntegrationConfigRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		Fail(c, err.Error())
		return
	}
	if err := h.service.Test(c.Request.Context(), c.Param("kind"), c.Param("provider"), &req); err != nil {
		Fail(c, err.Error())
		return
	}
	OK(c)
}

func (h *IntegrationConfig) Delete(c *gin.Context) {
	if err := h.service.Delete(c.Request.Context(), c.Param("kind"), c.Param("provider")); err != nil {
		Fail(c, err.Error())
		return
	}
	OK(c)
}
