package auth

import (
	"context"
	"errors"
	"strings"

	errs "gateway/internal/library/errors"
	"gateway/internal/library/zitadel"
	authmetaenum "gateway/internal/model/auth/domain/enum"
	domauth "gateway/internal/model/auth/domain/usecase"
	memberenum "gateway/internal/model/member/domain/enum"
	dommember "gateway/internal/model/member/domain/usecase"
	"gateway/internal/svc"
)

func resolveTenant(ctx context.Context, sc *svc.ServiceContext, slug string) (*dommember.TenantDTO, error) {
	if sc.MemberTenant == nil {
		return nil, errb.SysNotImplemented("member tenant not configured")
	}
	slug = strings.TrimSpace(slug)
	tenant, err := sc.MemberTenant.ResolveBySlug(ctx, slug)
	if err != nil {
		return nil, err
	}
	if tenant.Status != memberenum.TenantStatusActive.String() {
		return nil, errb.AuthForbidden("tenant registration is not allowed")
	}
	return tenant, nil
}

func wrapZitadelErr(err error) error {
	if err == nil {
		return nil
	}
	if errors.Is(err, zitadel.ErrNotConfigured) {
		return errb.SysNotImplemented("zitadel not configured").WithCause(err)
	}
	if errors.Is(err, zitadel.ErrUserAlreadyExists) {
		return errb.ResAlreadyExist("email already registered").WithCause(err)
	}
	if errors.Is(err, zitadel.ErrInvalidCredentials) {
		return errb.AuthUnauthorized("invalid credentials").WithCause(err)
	}
	if errors.Is(err, zitadel.ErrInvalidIDToken) {
		return errb.AuthUnauthorized("invalid id_token").WithCause(err)
	}
	if e := errs.FromError(err); e != nil {
		return err
	}
	return errb.SvcThirdParty("zitadel request failed").WithCause(err)
}

func registrationPurpose() memberenum.OTPPurpose {
	return memberenum.OTPPurposeRegistrationEmail
}

func recordRegistrationMeta(
	ctx context.Context,
	sc *svc.ServiceContext,
	tenantID, uid, inviteCodeID, acceptTermsVersion string,
	marketingOptIn bool,
	channel authmetaenum.RegistrationChannel,
) error {
	if sc.AuthRegistrationMeta == nil {
		return errb.SysNotImplemented("registration metadata not configured")
	}
	meta := RequestMetaFromContext(ctx)
	return sc.AuthRegistrationMeta.Record(ctx, &domauth.RecordRegistrationRequest{
		TenantID:           tenantID,
		UID:                uid,
		InviteCodeID:       inviteCodeID,
		AcceptTermsVersion: acceptTermsVersion,
		MarketingOptIn:     marketingOptIn,
		Channel:            channel,
		ClientIP:           strings.TrimSpace(meta.ClientIP),
		UserAgent:          strings.TrimSpace(meta.UserAgent),
	})
}

func requireRegistrationDeps(sc *svc.ServiceContext) error {
	if sc.Zitadel == nil {
		return errb.SysNotImplemented("zitadel not configured")
	}
	if sc.MemberLifecycle == nil {
		return errb.SysNotImplemented("member lifecycle not configured")
	}
	if sc.MemberOTP == nil {
		return errb.SysNotImplemented("member OTP not configured")
	}
	if sc.MemberVerifyRate == nil {
		return errb.SysNotImplemented("member verify rate not configured")
	}
	if sc.Notifier == nil {
		return errb.SysNotImplemented("notifier not configured")
	}
	return nil
}
