package inner

import (
	"fmt"

	"github.com/gin-gonic/gin"

	"github.com/tidbcloud/tidb-management-service/tempo-wrapper/internal/api/types"
	apiutils "github.com/tidbcloud/tidb-management-service/tempo-wrapper/internal/api/utils"
)

func CheckThreeArch(ctx *gin.Context) {
	req := &CheckThreeArchRequest{}
	if err := types.ShouldBindJSON(ctx, req); err != nil {
		types.BadRequestResp(ctx, fmt.Errorf("bind request body failed: %w", err))
		return
	}

	resp := &CheckThreeArchResponse{}
	for _, project := range req.Projects {
		if project.ProjectId == 0 || project.OrganizationId == 0 {
			continue
		}

		outputProject := &CheckThreeArchResponse_Project{
			ProjectId:      project.ProjectId,
			OrganizationId: project.OrganizationId,
			IsThreeArch:    false,
		}
		allow, err := apiutils.IsDedicatedAllow(ctx, project.OrganizationId, project.ProjectId)
		if err != nil {
			types.InternalErrorResp(ctx, fmt.Errorf("check dedicated allow failed: %w", err))
			return
		}
		if allow && !apiutils.IsLockOrgId(project.OrganizationId) {
			outputProject.IsThreeArch = true
		}
		resp.Projects = append(resp.Projects, outputProject)
	}

	types.SuccessRespNotProtoNames(ctx, resp)
}
