import Member from '../../../models/member.js'
import { connectDB } from '../../../utils/mongoose.js'

export default defineEventHandler(async (event) => {
  await connectDB()
  const member = await requireAuth(event)

  const body = await validateBody(event, peerSupportUpdateSchema)

  // Build update object for peer support settings
  const updateData = {
    'peerSupport.enabled': body.enabled || false,
    'peerSupport.skillTopics': body.skillTopics || [],
    'peerSupport.supportTopics': body.supportTopics || [],
    'peerSupport.availability': body.availability || '',
    'peerSupport.personalMessage': body.personalMessage || '',
    'peerSupport.slackUsername': body.slackUsername || '',
  }

  // If Slack username provided and peer support enabled, try to fetch Slack user ID
  if (body.enabled && body.slackUsername) {
    try {
      console.log(
        `[Peer Support] Attempting to fetch Slack user ID for: ${body.slackUsername}`,
      )

      const { getSlackService } = await import('../../../utils/slack.ts')
      const slackService = getSlackService()

      if (slackService) {
        console.log('[Peer Support] Slack service initialized, looking up user...')
        const slackUserId = await slackService.findUserIdByUsername(body.slackUsername)

        if (slackUserId) {
          updateData['slackUserId'] = slackUserId
          console.log(
            `[Peer Support] ✓ Found Slack user ID for ${body.slackUsername}: ${slackUserId}`,
          )

          console.log('[Peer Support] Opening DM channel...')
          const dmChannelId = await slackService.openDMChannel(slackUserId)

          if (dmChannelId) {
            updateData['peerSupport.slackDMChannelId'] = dmChannelId
            console.log(`[Peer Support] ✓ Got DM channel ID: ${dmChannelId}`)
          } else {
            console.warn('[Peer Support] Could not get DM channel ID')
          }
        } else {
          console.warn(
            `[Peer Support] Could not find Slack user ID for username: ${body.slackUsername}`,
          )
        }
      } else {
        console.log('[Peer Support] Slack service not configured, skipping user ID lookup')
      }
    } catch (error) {
      console.error('[Peer Support] Error fetching Slack user ID:', error.message)
      console.error('[Peer Support] Stack trace:', error.stack)
      // Continue anyway - we'll still save the username
    }
  }

  try {
    const updated = await Member.findByIdAndUpdate(
      member._id,
      { $set: updateData },
      { new: true, runValidators: true },
    )

    if (!updated) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Member not found',
      })
    }

    if (body.enabled) {
      logActivity(member._id, 'peer_support_enabled', {
        topics: [...(body.skillTopics || []), ...(body.supportTopics || [])]
      })
    } else {
      logActivity(member._id, 'peer_support_disabled', {})
    }

    return {
      success: true,
      peerSupport: updated.peerSupport,
    }
  } catch (error) {
    console.error('Peer support update error:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to update peer support settings',
    })
  }
})
