package handler

import (
	"baron-sso-backend/internal/domain"
	"baron-sso-backend/internal/service"
	"baron-sso-backend/internal/utils"
	"bytes"
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gofiber/fiber/v2"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
)

// --- Mocks ---

type MockKratosAdminServiceForConsent struct {
	mock.Mock
}

func (m *MockKratosAdminServiceForConsent) FindIdentityIDByIdentifier(ctx context.Context, identifier string) (string, error) {
	args := m.Called(ctx, identifier)
	return args.String(0), args.Error(1)
}

func (m *MockKratosAdminServiceForConsent) GetIdentity(ctx context.Context, id string) (*service.KratosIdentity, error) {
	args := m.Called(ctx, id)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).(*service.KratosIdentity), args.Error(1)
}

func (m *MockKratosAdminServiceForConsent) ListIdentities(ctx context.Context) ([]service.KratosIdentity, error) {
	return nil, nil
}

func (m *MockKratosAdminServiceForConsent) UpdateIdentity(ctx context.Context, identityID string, traits map[string]any, state string) (*service.KratosIdentity, error) {
	return nil, nil
}

func (m *MockKratosAdminServiceForConsent) CreateIdentity(ctx context.Context, traits map[string]any) (*service.KratosIdentity, error) {
	return nil, nil
}

func (m *MockKratosAdminServiceForConsent) DeleteIdentity(ctx context.Context, identityID string) error {
	return nil
}

func (m *MockKratosAdminServiceForConsent) UpdateIdentityPassword(ctx context.Context, identityID, newPassword string) error {
	return nil
}

func (m *MockKratosAdminServiceForConsent) ListIdentitySessions(ctx context.Context, identityID string) ([]service.KratosSession, error) {
	return nil, nil
}

func (m *MockKratosAdminServiceForConsent) GetSession(ctx context.Context, sessionID string) (*service.KratosSession, error) {
	return nil, nil
}

func (m *MockKratosAdminServiceForConsent) DeleteSession(ctx context.Context, sessionID string) error {
	return nil
}

func (m *MockKratosAdminServiceForConsent) CreateUser(ctx context.Context, user *domain.BrokerUser, password string) (string, error) {
	return "", nil
}

type MockTenantServiceForConsent struct {
	mock.Mock
}

func (m *MockTenantServiceForConsent) GetTenant(ctx context.Context, id string) (*domain.Tenant, error) {
	args := m.Called(ctx, id)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).(*domain.Tenant), args.Error(1)
}

func (m *MockTenantServiceForConsent) GetTenantBySlug(ctx context.Context, slug string) (*domain.Tenant, error) {
	return nil, nil
}

func (m *MockTenantServiceForConsent) GetTenantByDomain(ctx context.Context, domainName string) (*domain.Tenant, error) {
	return nil, nil
}

func (m *MockTenantServiceForConsent) ListTenants(ctx context.Context, limit, offset int, parentID string, search string) ([]domain.Tenant, int64, error) {
	return nil, 0, nil
}

func (m *MockTenantServiceForConsent) RegisterTenant(ctx context.Context, name, slug, tenantType, description string, domains []string, parentID *string, creatorID string) (*domain.Tenant, error) {
	return nil, nil
}

func (m *MockTenantServiceForConsent) RequestRegistration(ctx context.Context, name, slug, description string, domainName string, adminEmail string) (*domain.Tenant, error) {
	return nil, nil
}

func (m *MockTenantServiceForConsent) ApproveTenant(ctx context.Context, id string) error {
	return nil
}

func (m *MockTenantServiceForConsent) ListManageableTenants(ctx context.Context, userID string) ([]domain.Tenant, error) {
	args := m.Called(ctx, userID)
	return args.Get(0).([]domain.Tenant), args.Error(1)
}

func (m *MockTenantServiceForConsent) ListJoinedTenants(ctx context.Context, userID string) ([]domain.Tenant, error) {
	args := m.Called(ctx, userID)
	return args.Get(0).([]domain.Tenant), args.Error(1)
}

func (m *MockTenantServiceForConsent) IsDomainAllowed(ctx context.Context, domainName string) (bool, error) {
	return false, nil
}

func (m *MockTenantServiceForConsent) ProvisionTenantByDomain(ctx context.Context, domainName string) (*domain.Tenant, error) {
	return nil, nil
}

func (m *MockTenantServiceForConsent) SetKetoService(keto service.KetoService) {}

func (m *MockTenantServiceForConsent) DeleteTenantsBulk(ctx context.Context, ids []string) error {
	return nil
}

// --- Test Helpers ---

func newConsentTestApp(h *AuthHandler) *fiber.App {
	app := fiber.New()
	app.Get("/api/v1/auth/consent", h.GetConsentRequest)
	app.Post("/api/v1/auth/consent/accept", h.AcceptConsentRequest)
	return app
}

// --- Tests ---

func TestGetConsentRequest_Normal(t *testing.T) {
	// Mock Hydra transport
	transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
		if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-123" {
			return httpJSONAny(r, http.StatusOK, map[string]any{
				"challenge":       "challenge-123",
				"requested_scope": []string{"openid", "profile"},
				"skip":            false,
				"subject":         "user-123",
				"client": map[string]any{
					"client_id":   "client-app",
					"client_name": "Test App",
				},
			}), nil
		}
		return httpResponse(r, http.StatusNotFound, "not found"), nil
	})

	client := &http.Client{Transport: transport}

	origDefault := http.DefaultClient
	http.DefaultClient = client
	defer func() { http.DefaultClient = origDefault }()

	h := &AuthHandler{
		Hydra: &service.HydraAdminService{
			AdminURL:   "http://hydra.test",
			HTTPClient: client,
		},
	}
	app := newConsentTestApp(h)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/consent?consent_challenge=challenge-123", nil)
	resp, err := app.Test(req)

	assert.NoError(t, err)
	assert.Equal(t, http.StatusOK, resp.StatusCode)

	var body map[string]any
	json.NewDecoder(resp.Body).Decode(&body)

	assert.Equal(t, "challenge-123", body["challenge"])
	assert.Equal(t, false, body["skip"])
}

func TestGetConsentRequest_AddsMandatoryTenantScope(t *testing.T) {
	transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
		if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-tenant-scope" {
			return httpJSONAny(r, http.StatusOK, map[string]any{
				"challenge":       "challenge-tenant-scope",
				"requested_scope": []string{"openid", "profile"},
				"skip":            false,
				"subject":         "user-123",
				"client": map[string]any{
					"client_id":   "client-app",
					"client_name": "Test App",
					"metadata": map[string]any{
						"tenant_access_restricted": true,
						"allowed_tenants":          []string{"tenant-allow"},
						"structured_scopes": []map[string]any{
							{"name": "openid", "mandatory": true},
							{"name": "tenant", "mandatory": true, "locked": true},
							{"name": "profile", "mandatory": false},
						},
					},
				},
			}), nil
		}
		return httpResponse(r, http.StatusNotFound, "not found"), nil
	})

	client := &http.Client{Transport: transport}
	origDefault := http.DefaultClient
	http.DefaultClient = client
	defer func() { http.DefaultClient = origDefault }()

	mockTenantSvc := &MockTenantServiceForConsent{}
	mockKratosAdmin := &MockKratosAdminServiceForConsent{}

	// Mock profile resolution to allow tenant access
	mockKratosAdmin.On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
		ID: "user-123",
		Traits: map[string]any{
			"email": "user@example.com",
		},
	}, nil)

	mockTenantSvc.On("GetTenant", mock.Anything, "tenant-allow").Return(&domain.Tenant{
		ID:   "tenant-allow",
		Slug: "tenant-allow",
		Name: "Allowed Tenant",
	}, nil)

	// Mock hydration calls
	mockTenantSvc.On("ListJoinedTenants", mock.Anything, mock.Anything).Return([]domain.Tenant{
		{ID: "tenant-allow", Slug: "tenant-allow", Name: "Allowed Tenant"},
	}, nil)
	mockTenantSvc.On("ListManageableTenants", mock.Anything, mock.Anything).Return([]domain.Tenant{}, nil)

	h := &AuthHandler{
		Hydra: &service.HydraAdminService{
			AdminURL:   "http://hydra.test",
			HTTPClient: client,
		},
		TenantService: mockTenantSvc,
		KratosAdmin:   mockKratosAdmin,
	}
	app := newConsentTestApp(h)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/consent?consent_challenge=challenge-tenant-scope", nil)
	req.Header.Set("X-Mock-Role", "user")
	req.Header.Set("X-Tenant-ID", "tenant-allow")
	resp, err := app.Test(req)

	assert.NoError(t, err)
	assert.Equal(t, http.StatusOK, resp.StatusCode)

	var body map[string]any
	json.NewDecoder(resp.Body).Decode(&body)

	assert.Equal(t, []any{"openid", "tenant", "profile"}, body["requested_scope"])
	scopeDetails := body["scope_details"].(map[string]any)
	tenantDetail := scopeDetails["tenant"].(map[string]any)
	assert.Equal(t, true, tenantDetail["mandatory"])
}

func TestGetConsentRequest_Skip_AutoAccept(t *testing.T) {
	transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
		// Hydra: Get Consent Request
		if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-skip" {
			return httpJSONAny(r, http.StatusOK, map[string]any{
				"challenge":       "challenge-skip",
				"requested_scope": []string{"openid"},
				"skip":            true,
				"subject":         "user-123",
				"client": map[string]any{
					"client_id": "client-app",
				},
			}), nil
		}
		// Kratos: Get Identity
		if r.URL.Path == "/admin/identities/user-123" {
			return httpJSONAny(r, http.StatusOK, map[string]any{
				"id": "user-123",
				"traits": map[string]any{
					"email": "user@test.com",
				},
			}), nil
		}
		// Hydra: Accept Consent Request
		if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-skip" {
			return httpJSONAny(r, http.StatusOK, map[string]any{
				"redirect_to": "http://rp/cb",
			}), nil
		}
		return httpResponse(r, http.StatusNotFound, "not found"), nil
	})

	client := &http.Client{Transport: transport}
	origDefault := http.DefaultClient
	http.DefaultClient = client
	defer func() { http.DefaultClient = origDefault }()

	consentRepo := &mockConsentRepo{}
	rpUsageSink := &mockRPUsageEventSink{}
	mockKratosAdmin := &MockKratosAdminServiceForConsent{}

	h := &AuthHandler{
		Hydra: &service.HydraAdminService{
			AdminURL:   "http://hydra.test",
			HTTPClient: client,
		},
		KratosAdmin: mockKratosAdmin,
		ConsentRepo: consentRepo,
		RPUsageSink: rpUsageSink,
	}
	mockKratosAdmin.On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
		ID: "user-123",
		Traits: map[string]any{
			"email": "user@test.com",
		},
	}, nil)

	app := newConsentTestApp(h)
	req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/consent?consent_challenge=challenge-skip", nil)

	resp, err := app.Test(req)
	assert.NoError(t, err)
	assert.Equal(t, http.StatusOK, resp.StatusCode)

	var body map[string]any
	json.NewDecoder(resp.Body).Decode(&body)
	assert.Equal(t, "http://rp/cb", body["redirectTo"])
	assert.Equal(t, 1, len(rpUsageSink.events))
	assert.Equal(t, domain.RPUsageEventTypeAuthorizationGranted, rpUsageSink.events[0].EventType)
	assert.Equal(t, "client-app", rpUsageSink.events[0].ClientID)
	assert.Equal(t, "challenge-skip", rpUsageSink.events[0].CorrelationID)
	assert.Equal(t, true, rpUsageSink.events[0].Payload["auto_accepted"])
}

func TestAcceptConsentRequest_Normal(t *testing.T) {
	transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
		if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-accept" {
			return httpJSONAny(r, http.StatusOK, map[string]any{
				"challenge":       "challenge-accept",
				"requested_scope": []string{"openid", "profile"},
				"subject":         "user-123",
				"client": map[string]any{
					"client_id":   "client-app",
					"client_name": "Test App",
				},
			}), nil
		}
		if r.URL.Path == "/admin/identities/user-123" {
			return httpJSONAny(r, http.StatusOK, map[string]any{
				"id": "user-123",
				"traits": map[string]any{
					"email": "user@test.com",
				},
			}), nil
		}
		if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-accept" {
			return httpJSONAny(r, http.StatusOK, map[string]any{
				"redirect_to": "http://rp/cb",
			}), nil
		}
		return httpResponse(r, http.StatusNotFound, "not found"), nil
	})

	client := &http.Client{Transport: transport}
	origDefault := http.DefaultClient
	http.DefaultClient = client
	defer func() { http.DefaultClient = origDefault }()

	auditRepo := &mockAuditRepo{}
	consentRepo := &mockConsentRepo{}
	rpUsageSink := &mockRPUsageEventSink{}
	mockKratosAdmin := &MockKratosAdminServiceForConsent{}

	h := &AuthHandler{
		Hydra: &service.HydraAdminService{
			AdminURL:   "http://hydra.test",
			HTTPClient: client,
		},
		KratosAdmin: mockKratosAdmin,
		AuditRepo:   auditRepo,
		ConsentRepo: consentRepo,
		RPUsageSink: rpUsageSink,
	}
	mockKratosAdmin.On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
		ID: "user-123",
		Traits: map[string]any{
			"email": "user@test.com",
		},
	}, nil)

	app := newConsentTestApp(h)

	body, _ := json.Marshal(map[string]any{
		"consent_challenge": "challenge-accept",
		"grant_scope":       []string{"openid"},
	})
	req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/consent/accept", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")

	resp, err := app.Test(req)
	assert.NoError(t, err)
	assert.Equal(t, http.StatusOK, resp.StatusCode)

	assert.Equal(t, 1, len(auditRepo.logs))
	assert.Equal(t, "consent.granted", auditRepo.logs[0].EventType)
	assert.Equal(t, "user-123", auditRepo.logs[0].UserID)
	assert.Equal(t, "success", auditRepo.logs[0].Status)
	auditDetails, err := utils.ParseAuditDetails(auditRepo.logs[0].Details)
	assert.NoError(t, err)
	assert.Equal(t, "client-app", auditDetails["client_id"])
	assert.Equal(t, "Test App", auditDetails["client_name"])
	assert.Equal(t, []any{"openid"}, auditDetails["scopes"])
	assert.Equal(t, 1, len(rpUsageSink.events))
	assert.Equal(t, domain.RPUsageEventTypeAuthorizationGranted, rpUsageSink.events[0].EventType)
	assert.Equal(t, "user-123", rpUsageSink.events[0].Subject)
	assert.Equal(t, "client-app", rpUsageSink.events[0].ClientID)
	assert.Equal(t, "Test App", rpUsageSink.events[0].ClientName)
	assert.Equal(t, []string{"openid"}, []string(rpUsageSink.events[0].Scopes))
	assert.Equal(t, "hydra_consent", rpUsageSink.events[0].Source)
}

func TestAcceptConsentRequest_EnforcesMandatoryTenantScope(t *testing.T) {
	t.Setenv("APP_ENV", "dev")

	var capturedGrantScopes []string

	transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
		if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-tenant-accept" {
			return httpJSONAny(r, http.StatusOK, map[string]any{
				"challenge":       "challenge-tenant-accept",
				"requested_scope": []string{"openid", "profile"},
				"subject":         "user-123",
				"client": map[string]any{
					"client_id": "client-app",
					"metadata": map[string]any{
						"tenant_id":                "tenant-abc",
						"tenant_access_restricted": true,
						"allowed_tenants":          []string{"tenant-abc"},
						"structured_scopes": []map[string]any{
							{"name": "openid", "mandatory": true},
							{"name": "tenant", "mandatory": true, "locked": true},
							{"name": "profile", "mandatory": false},
						},
					},
				},
			}), nil
		}
		if r.URL.Path == "/admin/identities/user-123" {
			return httpJSONAny(r, http.StatusOK, map[string]any{
				"id": "user-123",
				"traits": map[string]any{
					"email": "user@test.com",
				},
			}), nil
		}
		if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-tenant-accept" {
			var payload map[string]any
			assert.NoError(t, json.NewDecoder(r.Body).Decode(&payload))
			for _, scope := range payload["grant_scope"].([]any) {
				capturedGrantScopes = append(capturedGrantScopes, scope.(string))
			}
			return httpJSONAny(r, http.StatusOK, map[string]any{
				"redirect_to": "http://rp/cb",
			}), nil
		}
		return httpResponse(r, http.StatusNotFound, "not found"), nil
	})

	client := &http.Client{Transport: transport}
	origDefault := http.DefaultClient
	http.DefaultClient = client
	defer func() { http.DefaultClient = origDefault }()

	mockKratosAdmin := &MockKratosAdminServiceForConsent{}

	h := &AuthHandler{
		Hydra: &service.HydraAdminService{
			AdminURL:   "http://hydra.test",
			HTTPClient: client,
		},
		KratosAdmin: mockKratosAdmin,
	}
	mockKratosAdmin.On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
		ID: "user-123",
		Traits: map[string]any{
			"email": "user@test.com",
		},
	}, nil)

	app := newConsentTestApp(h)

	body, _ := json.Marshal(map[string]any{
		"consent_challenge": "challenge-tenant-accept",
		"grant_scope":       []string{"openid", "profile"},
	})
	req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/consent/accept", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-Mock-Role", "user")
	req.Header.Set("X-Tenant-ID", "tenant-abc")

	resp, err := app.Test(req)
	assert.NoError(t, err)
	assert.Equal(t, http.StatusOK, resp.StatusCode)
	assert.Equal(t, []string{"openid", "tenant", "profile"}, capturedGrantScopes)
}
