package oci

import (
	"encoding/json"
	"testing"
)

func TestRewriteScimError(t *testing.T) {
	tests := []struct {
		name     string
		body     string
		wantCode string
		wantMsg  string
		passThru bool
	}{
		{
			name: "scim error with messageId",
			body: `{"schemas":["urn:ietf:params:scim:api:messages:2.0:Error"],` +
				`"detail":"Icon URL is too long.","status":"400",` +
				`"urn:ietf:params:scim:api:oracle:idcs:extension:messages:Error":{"messageId":"error.common.validation"}}`,
			wantCode: "error.common.validation",
			wantMsg:  "Icon URL is too long.",
		},
		{
			name:     "scim error without messageId",
			body:     `{"detail":"Missing required attribute.","status":"400"}`,
			wantCode: "IdcsError",
			wantMsg:  "Missing required attribute.",
		},
		{
			name:     "standard oci error passes through",
			body:     `{"code":"NotAuthorizedOrNotFound","message":"resource not found"}`,
			passThru: true,
		},
		{
			name:     "non-json passes through",
			body:     `<html>bad gateway</html>`,
			passThru: true,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			out := rewriteScimError([]byte(tt.body))
			if tt.passThru {
				if string(out) != tt.body {
					t.Fatalf("body rewritten unexpectedly: %s", out)
				}
				return
			}
			var got struct {
				Code    string `json:"code"`
				Message string `json:"message"`
			}
			if err := json.Unmarshal(out, &got); err != nil {
				t.Fatalf("unmarshal rewritten body: %v", err)
			}
			if got.Code != tt.wantCode || got.Message != tt.wantMsg {
				t.Errorf("got code=%q msg=%q, want code=%q msg=%q", got.Code, got.Message, tt.wantCode, tt.wantMsg)
			}
		})
	}
}
