package v1 import ( "context" "encoding/base64" "encoding/binary" "encoding/json" "errors" "fmt" "time" "github.com/google/uuid" "lincodex/backend/internal/adapter/primary/http/api" "lincodex/backend/internal/adapter/primary/http/problem" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" supportcase "lincodex/backend/internal/usecase/supportcase" ) const ( supportCaseCursorVersion = 1 supportCaseCursorBytes = 45 defaultSupportCaseLimit = 20 maxSupportCaseCursorUnixSeconds = uint64(253_402_300_799) ) // SupportOperations serves owner-scoped support-case creation and reads. type SupportOperations interface { Create(ctx context.Context, command supportcase.CreateCommand) (supportcase.CreateResult, error) GetMyCase(ctx context.Context, ownerID uuid.UUID, id domain.SupportCaseID) (domain.SupportCase, error) ListMyCases(ctx context.Context, command supportcase.ListCommand) (outbound.SupportCaseListPage, error) } // SupportHandler serves support-case operations without accepting an owner // identity from the request body or path. type SupportHandler struct { operations SupportOperations now func() time.Time } func NewSupportHandler(operations SupportOperations) *SupportHandler { if operations == nil { panic("v1.NewSupportHandler - support operations must not be nil") } return &SupportHandler{operations: operations, now: time.Now} } func (handler *Handler) CreateMySupportCase( ctx context.Context, request api.SupportCaseCreate, params api.CreateMySupportCaseParams, ) (api.CreateMySupportCaseRes, error) { if handler.support == nil { return handler.UnimplementedHandler.CreateMySupportCase(ctx, request, params) } return handler.support.CreateMySupportCase(ctx, request, params) } func (handler *Handler) GetMySupportCase( ctx context.Context, params api.GetMySupportCaseParams, ) (api.GetMySupportCaseRes, error) { if handler.support == nil { return handler.UnimplementedHandler.GetMySupportCase(ctx, params) } return handler.support.GetMySupportCase(ctx, params) } func (handler *Handler) ListMySupportCases( ctx context.Context, params api.ListMySupportCasesParams, ) (api.ListMySupportCasesRes, error) { if handler.support == nil { return handler.UnimplementedHandler.ListMySupportCases(ctx, params) } return handler.support.ListMySupportCases(ctx, params) } func (handler *SupportHandler) CreateMySupportCase( ctx context.Context, request api.SupportCaseCreate, params api.CreateMySupportCaseParams, ) (api.CreateMySupportCaseRes, error) { principal, ok := PrincipalFromContext(ctx) if !ok { return (*api.CreateMySupportCaseUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil } canonicalBody, err := json.Marshal(request) if err != nil { return nil, fmt.Errorf("SupportHandler.CreateMySupportCase - encode canonical request") } command, valid := supportCaseCreateCommand(request) if !valid { return (*api.CreateMySupportCaseBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil } command.ActorID = principal.UserID command.IdempotencyKey = params.IdempotencyKey command.CanonicalBody = canonicalBody result, err := handler.operations.Create(ctx, command) if err != nil { return supportCaseCreateFailure(ctx, err) } response, err := supportCaseResponse(result.Case, result.TargetLate) if err != nil { return nil, fmt.Errorf("SupportHandler.CreateMySupportCase - map case: %w", err) } return &api.SupportCaseHeaders{ CacheControl: api.CacheControlNoStoreNoStore, Response: response, }, nil } func (handler *SupportHandler) GetMySupportCase( ctx context.Context, params api.GetMySupportCaseParams, ) (api.GetMySupportCaseRes, error) { principal, ok := PrincipalFromContext(ctx) if !ok { return (*api.GetMySupportCaseUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil } supportCase, err := handler.operations.GetMyCase(ctx, principal.UserID, domain.SupportCaseID(params.CaseID)) if err != nil { return supportCaseReadFailure(ctx, err) } late := supportCase.ResponseTarget().IsLate(handler.now().UTC()) response, err := supportCaseResponse(supportCase, late) if err != nil { return nil, fmt.Errorf("SupportHandler.GetMySupportCase - map case: %w", err) } return &api.SupportCaseHeaders{ CacheControl: api.CacheControlNoStoreNoStore, Response: response, }, nil } func (handler *SupportHandler) ListMySupportCases( ctx context.Context, params api.ListMySupportCasesParams, ) (api.ListMySupportCasesRes, error) { principal, ok := PrincipalFromContext(ctx) if !ok { return (*api.ListMySupportCasesUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil } command, pointer := supportCaseListCommand(principal.UserID, params) if pointer != "" { return supportCaseListInvalid(ctx, pointer), nil } page, err := handler.operations.ListMyCases(ctx, command) if err != nil { switch { case errors.Is(err, supportcase.ErrForbidden), errors.Is(err, supportcase.ErrEmailNotVerified), errors.Is(err, outbound.ErrUserNotFound): return (*api.ListMySupportCasesUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil default: return nil, err } } items := make([]api.SupportCaseSummary, 0, len(page.Items)) for _, item := range page.Items { late := supportResponseTargetLate(item.ResponseTarget, handler.now().UTC()) summary, err := supportCaseSummaryResponse(item, late) if err != nil { return nil, fmt.Errorf("SupportHandler.ListMySupportCases - map summary: %w", err) } items = append(items, summary) } next := api.NilString{} next.SetToNull() if page.HasMore && len(page.Items) > 0 { cursor, err := encodeSupportCaseCursor(principal.UserID, outbound.SupportCasePositionOf(page.Items[len(page.Items)-1])) if err != nil { return nil, fmt.Errorf("SupportHandler.ListMySupportCases - encode cursor: %w", err) } next.SetTo(cursor) } return &api.SupportCaseListHeaders{ CacheControl: api.CacheControlNoStoreNoStore, Response: api.SupportCaseList{ Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}, }, }, nil } func supportCaseCreateCommand(request api.SupportCaseCreate) (supportcase.CreateCommand, bool) { var command supportcase.CreateCommand switch request.Type { case api.SupportCaseCreateSupportSupportCaseCreate: value := request.SupportCaseCreateSupport command.Type = domain.SupportCaseTypeSupport command.Description = string(value.Description) if object, ok := value.Object.Get(); ok { command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(object.Type), ID: object.ID} } if target, ok := value.AssessmentTarget.Get(); ok { command.AssessmentTarget = &domain.SupportCaseAssessmentTarget{ Specialization: domain.SpecializationCode(target.Specialization), Grade: domain.GradeCode(target.Grade), } } case api.SupportCaseCreateComplaintSupportCaseCreate: value := request.SupportCaseCreateComplaint command.Type = domain.SupportCaseTypeComplaint command.Description = string(value.Description) command.ComplaintReason = supportComplaintReasonPointer(domain.SupportCaseComplaintReason(value.ComplaintReason)) command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(value.Object.Type), ID: value.Object.ID} case api.SupportCaseCreateGradeAppealSupportCaseCreate: value := request.SupportCaseCreateGradeAppeal command.Type = domain.SupportCaseTypeGradeAppeal command.Description = string(value.Description) command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(value.Object.Type), ID: value.Object.ID} case api.SupportCaseCreateAnticheatAppealSupportCaseCreate: value := request.SupportCaseCreateAnticheatAppeal command.Type = domain.SupportCaseTypeAnticheatAppeal command.Description = string(value.Description) command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(value.Object.Type), ID: value.Object.ID} case api.SupportCaseCreateManualAssessmentSupportCaseCreate: value := request.SupportCaseCreateManualAssessment command.Type = domain.SupportCaseTypeManualAssessment command.Description = string(value.Description) command.AssessmentTarget = &domain.SupportCaseAssessmentTarget{ Specialization: domain.SpecializationCode(value.AssessmentTarget.Specialization), Grade: domain.GradeCode(value.AssessmentTarget.Grade), } if object, ok := value.Object.Get(); ok { command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(object.Type), ID: object.ID} } default: return supportcase.CreateCommand{}, false } return command, true } func supportCaseCreateFailure(ctx context.Context, err error) (api.CreateMySupportCaseRes, error) { switch { case errors.Is(err, supportcase.ErrForbidden), errors.Is(err, supportcase.ErrEmailNotVerified): return (*api.CreateMySupportCaseForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil case errors.Is(err, outbound.ErrUserNotFound): return (*api.CreateMySupportCaseUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil case errors.Is(err, outbound.ErrSupportCaseNotFound): return (*api.CreateMySupportCaseNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil case errors.Is(err, supportcase.ErrStateConflict), errors.Is(err, outbound.ErrSupportCaseConflict): return (*api.CreateMySupportCaseConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil case errors.Is(err, supportcase.ErrIdempotencyKeyReused): return (*api.CreateMySupportCaseUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil case errors.Is(err, supportcase.ErrInvalidIdempotencyKey): return (*api.CreateMySupportCaseBadRequest)( &problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response, ), nil case errors.Is(err, supportcase.ErrRateLimited): limited, ok := errors.AsType[*supportcase.RateLimitedError](err) if !ok || limited == nil { return nil, errors.New("SupportHandler.CreateMySupportCase - rate limit error has no retry interval") } return problem.RateLimited(ctx, wholeSeconds(limited.RetryAfter)), nil case errors.Is(err, supportcase.ErrInvalidCreateRequest), errors.Is(err, domain.ErrInvalidSupportCase): fieldError, ok := errors.AsType[*domain.SupportCaseFieldError](err) if !ok { return (*api.CreateMySupportCaseBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil } return (*api.CreateMySupportCaseBadRequest)( &problem.InvalidField(ctx, api.ProblemFieldLocationBody, fieldError.Pointer).Response, ), nil default: return nil, err } } func supportCaseReadFailure(ctx context.Context, err error) (api.GetMySupportCaseRes, error) { switch { case errors.Is(err, supportcase.ErrForbidden), errors.Is(err, supportcase.ErrEmailNotVerified), errors.Is(err, outbound.ErrUserNotFound): return (*api.GetMySupportCaseUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil case errors.Is(err, outbound.ErrSupportCaseNotFound): return (*api.GetMySupportCaseNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil default: return nil, err } } func supportCaseListCommand(actorID uuid.UUID, params api.ListMySupportCasesParams) (supportcase.ListCommand, string) { limit, ok := params.Limit.Get() if !ok { limit = defaultSupportCaseLimit } if limit < 1 || limit > outbound.MaxSupportCasePageSize { return supportcase.ListCommand{}, "limit" } command := supportcase.ListCommand{ActorID: actorID, Limit: limit} if cursor, ok := params.Cursor.Get(); ok { position, err := decodeSupportCaseCursor(cursor, actorID) if err != nil { return supportcase.ListCommand{}, "cursor" } command.After = &position } return command, "" } func supportCaseListInvalid(ctx context.Context, pointer string) *api.ListMySupportCasesBadRequest { return (*api.ListMySupportCasesBadRequest)( &problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response, ) } func encodeSupportCaseCursor(actorID uuid.UUID, position outbound.SupportCaseListPosition) (string, error) { seconds, nanos := position.CreatedAt.Unix(), position.CreatedAt.Nanosecond() if actorID == uuid.Nil || position.ID.IsZero() || !validSupportCaseCursorTime(position.CreatedAt) || seconds < 0 || nanos < 0 || nanos >= 1_000_000_000 { return "", errors.New("support case cursor requires an actor and a valid position") } var value [supportCaseCursorBytes]byte value[0] = supportCaseCursorVersion copy(value[1:17], actorID[:]) binary.BigEndian.PutUint64(value[17:25], uint64(seconds)) binary.BigEndian.PutUint32(value[25:29], uint32(nanos)) caseID := position.ID.UUID() copy(value[29:45], caseID[:]) return base64.RawURLEncoding.EncodeToString(value[:]), nil } func decodeSupportCaseCursor(cursor string, actorID uuid.UUID) (outbound.SupportCaseListPosition, error) { value, err := base64.RawURLEncoding.DecodeString(cursor) if err != nil || len(value) != supportCaseCursorBytes || actorID == uuid.Nil || base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != supportCaseCursorVersion || uuid.UUID(value[1:17]) != actorID { return outbound.SupportCaseListPosition{}, errors.New("support case cursor is invalid") } nanos := binary.BigEndian.Uint32(value[25:29]) caseID := uuid.UUID(value[29:45]) seconds := binary.BigEndian.Uint64(value[17:25]) if nanos >= 1_000_000_000 || caseID == uuid.Nil || seconds > maxSupportCaseCursorUnixSeconds { return outbound.SupportCaseListPosition{}, errors.New("support case cursor position is invalid") } createdAt := time.Unix(int64(seconds), int64(nanos)).UTC() if !validSupportCaseCursorTime(createdAt) { return outbound.SupportCaseListPosition{}, errors.New("support case cursor timestamp is invalid") } return outbound.SupportCaseListPosition{CreatedAt: createdAt, ID: domain.SupportCaseID(caseID)}, nil } func validSupportCaseCursorTime(value time.Time) bool { utc := value.UTC() return !value.IsZero() && utc.Year() >= 1 && utc.Year() <= 9999 && value.Unix() >= 0 && value.Nanosecond()%int(time.Microsecond) == 0 } func supportCaseResponse(supportCase domain.SupportCase, targetLate bool) (api.SupportCase, error) { snapshot := supportCase.Snapshot() target, err := checkedSupportResponseTarget(snapshot.ResponseTarget, targetLate) if err != nil { return api.SupportCase{}, err } response := api.SupportCase{ ID: snapshot.ID.UUID(), Number: api.SupportCaseNumber(snapshot.Number), Type: api.SupportCaseType(snapshot.Type), Status: api.SupportCaseStatus(snapshot.Status), Description: api.SupportCaseDescription(snapshot.Description), ResponseTarget: target, History: make([]api.SupportCaseEvent, 0, len(snapshot.History)), CreatedAt: api.Timestamp(snapshot.CreatedAt), UpdatedAt: api.Timestamp(snapshot.UpdatedAt), } response.Object = supportCaseObject(snapshot.Object) response.AssessmentTarget = supportCaseAssessmentTarget(snapshot.AssessmentTarget) response.ComplaintReason = supportCaseComplaintReason(snapshot.ComplaintReason) response.RubricVersion = supportCaseInt32(snapshot.RubricVersion) response.Decision = supportCaseDecision(snapshot.Decision) for _, event := range snapshot.History { response.History = append(response.History, supportCaseEvent(event)) } return response, nil } func supportCaseSummaryResponse(summary domain.SupportCaseSummary, targetLate bool) (api.SupportCaseSummary, error) { target, err := checkedSupportResponseTarget(summary.ResponseTarget, targetLate) if err != nil { return api.SupportCaseSummary{}, err } response := api.SupportCaseSummary{ ID: summary.ID.UUID(), Number: api.SupportCaseNumber(summary.Number), Type: api.SupportCaseType(summary.Type), Status: api.SupportCaseStatus(summary.Status), Object: supportCaseObject(summary.Object), AssessmentTarget: supportCaseAssessmentTarget(summary.AssessmentTarget), ResponseTarget: target, CreatedAt: api.Timestamp(summary.CreatedAt), UpdatedAt: api.Timestamp(summary.UpdatedAt), } if summary.DecisionOutcome == nil { response.DecisionOutcome.SetToNull() } else { response.DecisionOutcome.SetTo(api.SupportCaseDecisionOutcome(*summary.DecisionOutcome)) } return response, nil } func checkedSupportResponseTarget(snapshot domain.SupportResponseTargetSnapshot, late bool) (api.SupportResponseTarget, error) { if _, err := domain.NewSupportResponseTarget(snapshot); err != nil { return api.SupportResponseTarget{}, err } response := api.SupportResponseTarget{ Kind: api.SupportResponseTargetKindOperationalGoal, BusinessDays: int32(snapshot.BusinessDays), DueAt: api.Timestamp(snapshot.DueAt), Late: late, PolicyVersion: snapshot.PolicyVersion, } if snapshot.AnsweredAt == nil { response.AnsweredAt.SetToNull() } else { response.AnsweredAt.SetTo(api.Timestamp(*snapshot.AnsweredAt)) } return response, nil } func supportResponseTargetLate(snapshot domain.SupportResponseTargetSnapshot, at time.Time) bool { target, err := domain.NewSupportResponseTarget(snapshot) return err == nil && target.IsLate(at) } func supportCaseObject(reference *domain.SupportCaseReference) api.NilSupportCaseObjectReference { var result api.NilSupportCaseObjectReference if reference == nil { result.SetToNull() return result } result.SetTo(api.SupportCaseObjectReference{Type: api.SupportCaseObjectType(reference.Type), ID: reference.ID}) return result } func supportCaseAssessmentTarget(target *domain.SupportCaseAssessmentTarget) api.NilSupportCaseAssessmentTarget { var result api.NilSupportCaseAssessmentTarget if target == nil { result.SetToNull() return result } result.SetTo(api.SupportCaseAssessmentTarget{ Specialization: api.SpecializationCode(target.Specialization), Grade: api.GradeCode(target.Grade), }) return result } func supportCaseComplaintReason(reason *domain.SupportCaseComplaintReason) api.NilSupportCaseComplaintReason { var result api.NilSupportCaseComplaintReason if reason == nil { result.SetToNull() return result } result.SetTo(api.SupportCaseComplaintReason(*reason)) return result } func supportCaseInt32(value *int32) api.NilInt32 { var result api.NilInt32 if value == nil { result.SetToNull() return result } result.SetTo(*value) return result } func supportCaseDecision(decision *domain.SupportCaseDecisionSnapshot) api.NilSupportCaseDecision { var result api.NilSupportCaseDecision if decision == nil { result.SetToNull() return result } result.SetTo(api.SupportCaseDecision{ Outcome: api.SupportCaseDecisionOutcome(decision.Outcome), Reason: api.SupportCasePublicText(decision.Reason), DecidedAt: api.Timestamp(decision.DecidedAt), }) return result } func supportCaseEvent(event domain.SupportCaseEventSnapshot) api.SupportCaseEvent { result := api.SupportCaseEvent{ Sequence: event.Sequence, Kind: api.SupportCaseEventKind(event.Kind), Actor: api.SupportCaseActorKind(event.Actor), OccurredAt: api.Timestamp(event.OccurredAt), } if event.Status == nil { result.Status.SetToNull() } else { result.Status.SetTo(api.SupportCaseStatus(*event.Status)) } if event.Message == nil { result.Message.SetToNull() } else { result.Message.SetTo(api.SupportCasePublicText(*event.Message)) } return result } func supportComplaintReasonPointer(value domain.SupportCaseComplaintReason) *domain.SupportCaseComplaintReason { return &value }