package handlers

import (
	"net/http"
	"strings"
	"testing"
)

func TestInferHelicopterErrorCode_StatusPrefixSync(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name   string
		status int
		title  string
		detail string
		prefix string
		code   string
	}{
		{
			name:   "duplicate uses conflict",
			status: http.StatusConflict,
			title:  "Conflict",
			detail: "Serial number already exists",
			prefix: "409",
			code:   "HELICOPTER_DUPLICATE",
		},
		{
			name:   "validation payload",
			status: http.StatusUnprocessableEntity,
			title:  "Validation error",
			detail: "designation, identifier, and type are required",
			prefix: "422",
			code:   "HELICOPTER_INVALID_PAYLOAD",
		},
		{
			name:   "validation invalid type",
			status: http.StatusUnprocessableEntity,
			title:  "Validation error",
			detail: "type is oneof",
			prefix: "422",
			code:   "HELICOPTER_INVALID_TYPE",
		},
		{
			name:   "bad request create failed",
			status: http.StatusBadRequest,
			title:  "Create failed",
			detail: "some low-level error",
			prefix: "400",
			code:   "HELICOPTER_CREATE_FAILED",
		},
		{
			name:   "not found",
			status: http.StatusNotFound,
			title:  "Not found",
			detail: "helicopter not found",
			prefix: "404",
			code:   "HELICOPTER_NOT_FOUND",
		},
	}

	for _, tt := range tests {
		tt := tt
		t.Run(tt.name, func(t *testing.T) {
			code, errorCode := inferHelicopterErrorCode(tt.status, tt.title, tt.detail)
			if code != tt.code {
				t.Fatalf("unexpected code: got=%s want=%s", code, tt.code)
			}
			if !strings.HasPrefix(errorCode, tt.prefix) {
				t.Fatalf("error_code prefix mismatch: status=%d code=%s error_code=%s", tt.status, code, errorCode)
			}
		})
	}
}

func TestInferHelicopterErrorCode_400NeverReturns409Code(t *testing.T) {
	t.Parallel()

	_, errorCode := inferHelicopterErrorCode(http.StatusBadRequest, "Create failed", "already exists")
	if strings.HasPrefix(errorCode, "409") {
		t.Fatalf("bad request must not map to 409-prefixed error_code, got=%s", errorCode)
	}
}
