package trigger

import (
	"github.com/tidbcloud/AgentTeam/internal/api"
	"github.com/tidbcloud/AgentTeam/internal/api/dto"
	"github.com/tidbcloud/AgentTeam/internal/api/dto/converter"
)

// Get handles GET /api/v1/workspaces/:workspaceId/triggers/:triggerId.
// It retrieves a single trigger by ID for the authenticated user in the current workspace.
func (handler *DetailHandler) Get(request api.WorkspaceScopedRequest) (api.Response, error) {
	result, err := handler.triggerService.GetForOwner(request.Context(), request.UserID(), request.WorkspaceID(), scheduleOrTriggerID(request.Gin))
	if err != nil {
		return api.Response{}, err
	}
	return api.OK(result), nil
}

// Update handles PATCH /api/v1/workspaces/:workspaceId/triggers/:triggerId.
// It updates an existing trigger by ID using fields from the JSON request body.
func (handler *DetailHandler) Update(r api.WorkspaceScopedJSON[dto.TriggerMutationRequest]) (api.Response, error) {
	body := r.Body
	result, err := handler.triggerService.UpdateForOwner(
		r.Context(),
		r.UserID(),
		r.WorkspaceID(),
		scheduleOrTriggerID(r.Gin),
		converter.FromTriggerMutationRequest(body),
	)
	if err != nil {
		return api.Response{}, err
	}
	return api.OK(result), nil
}

// Delete handles DELETE /api/v1/workspaces/:workspaceId/triggers/:triggerId.
// It deletes a trigger by ID for the authenticated user in the current workspace.
func (handler *DetailHandler) Delete(request api.WorkspaceScopedRequest) (api.Response, error) {
	if err := handler.triggerService.DeleteForOwner(request.Context(), request.UserID(), request.WorkspaceID(), scheduleOrTriggerID(request.Gin)); err != nil {
		return api.Response{}, err
	}
	return api.OK(dto.TriggerDeleteResponse{Deleted: true}), nil
}
