package aml

import (
	"context"

	"github.com/niels/banking-app/backend/internal/domain"
	"github.com/niels/banking-app/backend/internal/integrations/sanctions"
)

type Service struct {
	repo      *Repository
	sanctions sanctions.Provider
}

func NewService(repo *Repository, sanctionsProvider sanctions.Provider) *Service {
	return &Service{repo: repo, sanctions: sanctionsProvider}
}

func (s *Service) ScreenKYCProfile(ctx context.Context, profile domain.KYCProfile) (domain.AMLScreening, *domain.AMLCase, error) {
	result, err := s.sanctions.ScreenPerson(ctx, sanctions.ScreenPersonParams{
		UserID:      profile.UserID,
		LegalName:   profile.LegalName,
		DateOfBirth: profile.DateOfBirth,
		Country:     profile.Country,
	})
	if err != nil {
		return domain.AMLScreening{}, nil, err
	}

	screening, err := s.repo.CreateScreening(ctx, CreateScreeningParams{
		UserID:        profile.UserID,
		KYCProfileID:  profile.ID,
		ScreeningType: "kyc_onboarding",
		Result:        result,
	})
	if err != nil {
		return domain.AMLScreening{}, nil, err
	}

	if !result.Matched && result.RiskScore < 70 {
		return screening, nil, nil
	}

	severity := "medium"
	if result.RiskScore >= 90 {
		severity = "high"
	}

	amlCase, err := s.repo.CreateCase(ctx, screening, "sanctions_review", severity, result.Status)
	if err != nil {
		return domain.AMLScreening{}, nil, err
	}

	return screening, &amlCase, nil
}
