package auth

import (
	"context"

	"hyapp/pkg/appcode"
	"hyapp/pkg/xerr"
	authdomain "hyapp/services/user-service/internal/domain/auth"
	"hyapp/services/user-service/internal/storage/mysql/shared"
)

func (r *Repository) RecordLoginAudit(ctx context.Context, audit authdomain.LoginAudit) error {
	// 审计表不能包含密码、三方 credential 或 refresh token 原文。
	_, err := r.db.ExecContext(ctx, `
		INSERT INTO login_audit (app_code, request_id, user_id, login_type, provider, channel, platform, app_version, build_number, result, failure_code, client_ip, ip_country_code, blocked, block_reason, user_agent, created_at_ms)
		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
	`, appcode.Normalize(audit.AppCode), audit.RequestID, nullableUserID(audit.UserID), audit.LoginType, shared.NullableString(audit.Provider), audit.Channel, audit.Platform, audit.AppVersion, audit.BuildNumber, audit.Result, shared.NullableString(audit.FailureCode), shared.NullableString(audit.ClientIP), audit.IPCountryCode, audit.Blocked, audit.BlockReason, shared.NullableString(audit.UserAgent), audit.CreatedAtMs)
	return err
}

func (r *Repository) MarkLoginAuditBlocked(ctx context.Context, requestID string, userID int64, countryCode string, blockReason string) error {
	_, err := r.db.ExecContext(ctx, `
		UPDATE login_audit
		SET result = 'revoked',
		    failure_code = ?,
		    ip_country_code = ?,
		    blocked = 1,
		    block_reason = ?
		WHERE app_code = ? AND request_id = ? AND user_id = ?
	`, string(xerr.AuthLoginBlocked), countryCode, blockReason, appcode.FromContext(ctx), requestID, userID)
	return err
}

func nullableUserID(userID int64) any {
	if userID <= 0 {
		// 审计中未知用户写 NULL。
		return nil
	}

	return userID
}
