import { GraphQLError } from 'graphql'

import { prisma } from '../../../lib/prisma'
import { Context } from '../../context'
import { DomainResolvers } from '../shared/types'

// Referrals Domain Resolvers - управление реферальной системой (мигрировано из referrals.ts)

// =============================================================================
// 🔐 AUTHENTICATION HELPERS
// =============================================================================

const withAuth = (resolver: any) => {
  return async (parent: any, args: any, context: Context) => {
    console.log('🔐 REFERRALS DOMAIN AUTH CHECK:', { 
      hasUser: !!context.user, 
      userId: context.user?.id,
      organizationId: context.user?.organizationId, 
    })
    if (!context.user) {
      console.error('❌ AUTH FAILED: No user in context')
      throw new GraphQLError('Требуется авторизация', {
        extensions: { code: 'UNAUTHENTICATED' },
      })
    }
    console.log('✅ AUTH PASSED: Calling resolver')
    try {
      const result = await resolver(parent, args, context)
      console.log('🎯 RESOLVER RESULT TYPE:', typeof result, result === null ? 'NULL RESULT!' : 'Has result')
      return result
    } catch (error) {
      console.error('💥 RESOLVER ERROR:', error)
      throw error
    }
  }
}

const checkOrganizationAccess = async (userId: string) => {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    include: { organization: true },
  })

  if (!user?.organizationId) {
    throw new GraphQLError('Пользователь не привязан к организации', {
      extensions: { code: 'FORBIDDEN' },
    })
  }

  return user
}

// =============================================================================
// 🔗 REFERRALS DOMAIN RESOLVERS
// =============================================================================

export const referralResolvers: DomainResolvers = {
  Query: {
    // Получить реферальную ссылку текущего пользователя
    myReferralLink: withAuth(async (_: unknown, __: unknown, context: Context) => {
      console.log('🔍 MY_REFERRAL_LINK DOMAIN QUERY STARTED:', { userId: context.user?.id })
      try {
        const user = await checkOrganizationAccess(context.user!.id)
        console.log('🔍 MY_REFERRAL_LINK - USER DATA:', { 
          userId: user.id, 
          organizationId: user.organizationId,
          hasOrganization: !!user.organization, 
        })

        const organization = await prisma.organization.findUnique({
          where: { id: user.organizationId! },
          select: { 
            id: true,
            referralCode: true, 
            inn: true,
            type: true,
            name: true, 
          },
        })

        console.log('🔍 MY_REFERRAL_LINK - ORGANIZATION DATA:', { 
          organizationFound: !!organization,
          organizationId: organization?.id,
          referralCode: organization?.referralCode,
          inn: organization?.inn,
          type: organization?.type,
          name: organization?.name,
        })

        if (!organization?.referralCode) {
          console.error('❌ MY_REFERRAL_LINK - MISSING REFERRAL CODE:', {
            organization: organization,
            hasOrganization: !!organization,
            referralCodeExists: !!organization?.referralCode,
          })
          throw new GraphQLError('Реферальный код не найден')
        }

        const link = `${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/register?ref=${organization.referralCode}`

        console.log('✅ MY_REFERRAL_LINK DOMAIN SUCCESS:', { link })
        return link || 'http://localhost:3000/register?ref=ERROR'
      } catch (error) {
        console.error('❌ MY_REFERRAL_LINK DOMAIN ERROR:', error)
        throw error
      }
    }),

    // Получить партнерскую ссылку текущего пользователя
    myPartnerLink: withAuth(async (_: unknown, __: unknown, context: Context) => {
      console.log('🔍 MY_PARTNER_LINK DOMAIN QUERY STARTED:', { userId: context.user?.id })
      try {
        const user = await checkOrganizationAccess(context.user!.id)

        const organization = await prisma.organization.findUnique({
          where: { id: user.organizationId! },
          select: { referralCode: true },
        })

        if (!organization?.referralCode) {
          throw new GraphQLError('Реферальный код не найден')
        }

        const link = `${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/register?partner=${organization.referralCode}`

        console.log('✅ MY_PARTNER_LINK DOMAIN SUCCESS:', { link })
        return link
      } catch (error) {
        console.error('❌ MY_PARTNER_LINK DOMAIN ERROR:', error)
        throw error
      }
    }),

    // Получить статистику по рефералам
    myReferralStats: withAuth(async (_: unknown, __: unknown, context: Context) => {
      console.log('🔍 MY_REFERRAL_STATS DOMAIN QUERY STARTED:', { userId: context.user?.id })
      try {
        await checkOrganizationAccess(context.user!.id)

        // TODO: Реализовать настоящую статистику рефералов
        // Исправленная заглушка соответствующая GraphQL схеме
        const result = {
          totalPartners: 0,
          totalSpheres: 0,
          monthlyPartners: 0,
          monthlySpheres: 0,
          referralsByType: [
            { type: 'SELLER', count: 0, spheres: 0 },
            { type: 'WHOLESALE', count: 0, spheres: 0 },
            { type: 'FULFILLMENT', count: 0, spheres: 0 },
            { type: 'LOGIST', count: 0, spheres: 0 },
          ],
          referralsBySource: [
            { source: 'REFERRAL_LINK', count: 0, spheres: 0 },
            { source: 'AUTO_BUSINESS', count: 0, spheres: 0 },
          ],
        }

        console.log('✅ MY_REFERRAL_STATS DOMAIN SUCCESS:', { result })
        return result
      } catch (error) {
        console.error('❌ MY_REFERRAL_STATS DOMAIN ERROR:', error)
        throw error
      }
    }),

    // Получить список рефералов
    myReferrals: withAuth(async (_: unknown, _args: unknown, context: Context) => {
      console.log('🔍 MY_REFERRALS DOMAIN QUERY STARTED:', { userId: context.user?.id })
      try {
        await checkOrganizationAccess(context.user!.id)

        // TODO: Реализовать настоящий список рефералов
        // Временная заглушка для отладки
        const result = {
          referrals: [],
          totalCount: 0,
          totalPages: 0,
        }

        console.log('✅ MY_REFERRALS DOMAIN SUCCESS:', { result })
        return result
      } catch (error) {
        console.error('❌ MY_REFERRALS DOMAIN ERROR:', error)
        return {
          referrals: [],
          totalCount: 0,
          totalPages: 0,
        }
      }
    }),

    // Получить историю транзакций рефералов
    myReferralTransactions: withAuth(async (_: unknown, args: { limit?: number; offset?: number }, context: Context) => {
      console.log('🔍 MY_REFERRAL_TRANSACTIONS DOMAIN QUERY STARTED:', { userId: context.user?.id, args })
      try {
        await checkOrganizationAccess(context.user!.id)

        // TODO: Реализовать настоящую историю транзакций рефералов
        // Временная заглушка для отладки
        const result = {
          transactions: [],
          totalCount: 0,
        }

        console.log('✅ MY_REFERRAL_TRANSACTIONS DOMAIN SUCCESS:', { result })
        return result
      } catch (error) {
        console.error('❌ MY_REFERRAL_TRANSACTIONS DOMAIN ERROR:', error)
        return {
          transactions: [],
          totalCount: 0,
        }
      }
    }),
  },

  Mutation: {
    // TODO: Добавить мутации для реферальной системы при необходимости
  },
}