package org

import (
	"net/http"
	"strings"

	"github.com/tidbcloud/AgentTeam/internal/api"
	"github.com/tidbcloud/AgentTeam/internal/api/dto"
	"github.com/tidbcloud/AgentTeam/internal/api/dto/converter"
	"github.com/tidbcloud/AgentTeam/internal/store/organization"

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

func (handler *ProviderHandler) LLMProxyKeysList(ctx *gin.Context) {
	authenticated, ok := api.AuthenticatedUserFromContext(ctx)
	if !ok {
		api.Error(ctx, http.StatusUnauthorized, "Unauthorized")
		return
	}
	orgs, ok := handler.organizationProvider()
	if !ok {
		api.Error(ctx, http.StatusNotFound, "Organization provider not installed")
		return
	}
	organizationID := strings.TrimSpace(ctx.Param("orgId"))
	if organizationID == "" {
		api.Error(ctx, http.StatusBadRequest, "Invalid request")
		return
	}
	items, err := orgs.ListOrganizationLLMProxyKeysForUser(ctx.Request.Context(), authenticated.User.ID, organizationID)
	if err != nil {
		api.StoreError(ctx, err)
		return
	}
	ctx.JSON(http.StatusOK, converter.ToOrgLLMProxyKeyViews(items))
}

func (handler *ProviderHandler) LLMProxyKeyCreate(ctx *gin.Context) {
	authenticated, ok := api.AuthenticatedUserFromContext(ctx)
	if !ok {
		api.Error(ctx, http.StatusUnauthorized, "Unauthorized")
		return
	}
	orgs, ok := handler.organizationProvider()
	if !ok {
		api.Error(ctx, http.StatusNotFound, "Organization provider not installed")
		return
	}
	organizationID := strings.TrimSpace(ctx.Param("orgId"))
	if organizationID == "" {
		api.Error(ctx, http.StatusBadRequest, "Invalid request")
		return
	}
	var request dto.OrganizationLLMProxyKeyCreateRequest
	if err := ctx.ShouldBindJSON(&request); err != nil {
		api.Error(ctx, http.StatusBadRequest, "Invalid request body")
		return
	}
	item, err := orgs.CreateOrganizationLLMProxyKeyForUser(ctx.Request.Context(), authenticated.User.ID, organizationID, organization.CreateOrganizationLLMProxyKeyParams{
		Label: request.Label,
	})
	if err != nil {
		api.StoreError(ctx, err)
		return
	}
	ctx.JSON(http.StatusOK, converter.ToOrgLLMProxyKeyCreateResult(item))
}

func (handler *ProviderHandler) LLMProxyKeyDelete(ctx *gin.Context) {
	authenticated, ok := api.AuthenticatedUserFromContext(ctx)
	if !ok {
		api.Error(ctx, http.StatusUnauthorized, "Unauthorized")
		return
	}
	orgs, ok := handler.organizationProvider()
	if !ok {
		api.Error(ctx, http.StatusNotFound, "Organization provider not installed")
		return
	}
	organizationID := strings.TrimSpace(ctx.Param("orgId"))
	keyID := strings.TrimSpace(ctx.Param("keyId"))
	if organizationID == "" || keyID == "" {
		api.Error(ctx, http.StatusBadRequest, "Invalid request")
		return
	}
	if err := orgs.DeleteOrganizationLLMProxyKeyForUser(ctx.Request.Context(), authenticated.User.ID, organizationID, keyID); err != nil {
		api.StoreError(ctx, err)
		return
	}
	ctx.JSON(http.StatusOK, dto.EmptyResponse{})
}
