import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import {
  confluenceDeleteCommentContract,
  confluenceUpdateCommentContract,
} from '@/lib/api/contracts/selectors/confluence'
import { parseRequest } from '@/lib/api/server'
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
import { validateJiraCloudId } from '@/lib/core/security/input-validation'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { getConfluenceCloudId } from '@/tools/confluence/utils'
import { parseAtlassianErrorMessage } from '@/tools/jira/utils'

const logger = createLogger('ConfluenceCommentAPI')

export const dynamic = 'force-dynamic'

// Update a comment
export const PUT = withRouteHandler(async (request: NextRequest) => {
  try {
    const auth = await checkSessionOrInternalAuth(request)
    if (!auth.success || !auth.userId) {
      return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
    }

    const parsed = await parseRequest(confluenceUpdateCommentContract, request, {})
    if (!parsed.success) return parsed.response

    const { domain, accessToken, cloudId: providedCloudId, commentId, comment } = parsed.data.body

    const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))

    const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
    if (!cloudIdValidation.isValid) {
      return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
    }

    // Detect comment type — try footer-comments first, fall back to inline-comments
    const apiBase = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2`
    let commentEndpoint = 'footer-comments'
    let getResponse = await fetch(`${apiBase}/footer-comments/${commentId}`, {
      headers: {
        Accept: 'application/json',
        Authorization: `Bearer ${accessToken}`,
      },
    })

    if (getResponse.status === 404) {
      commentEndpoint = 'inline-comments'
      getResponse = await fetch(`${apiBase}/inline-comments/${commentId}`, {
        headers: {
          Accept: 'application/json',
          Authorization: `Bearer ${accessToken}`,
        },
      })
    }

    if (!getResponse.ok) {
      const errorText = await getResponse.text()
      throw new Error(
        parseAtlassianErrorMessage(getResponse.status, getResponse.statusText, errorText)
      )
    }

    const currentComment = await getResponse.json()
    const currentVersion = currentComment.version?.number || 1

    const url = `${apiBase}/${commentEndpoint}/${commentId}`

    const updateBody = {
      body: {
        representation: 'storage',
        value: comment,
      },
      version: {
        number: currentVersion + 1,
        message: 'Updated via Sim',
      },
    }

    const response = await fetch(url, {
      method: 'PUT',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: `Bearer ${accessToken}`,
      },
      body: JSON.stringify(updateBody),
    })

    if (!response.ok) {
      const errorText = await response.text()
      logger.error('Confluence API error response:', {
        status: response.status,
        statusText: response.statusText,
        error: errorText,
      })
      return NextResponse.json(
        { error: parseAtlassianErrorMessage(response.status, response.statusText, errorText) },
        { status: response.status }
      )
    }

    const data = await response.json()
    return NextResponse.json(data)
  } catch (error) {
    logger.error('Error updating Confluence comment:', error)
    return NextResponse.json(
      { error: (error as Error).message || 'Internal server error' },
      { status: 500 }
    )
  }
})

// Delete a comment
export const DELETE = withRouteHandler(async (request: NextRequest) => {
  try {
    const auth = await checkSessionOrInternalAuth(request)
    if (!auth.success || !auth.userId) {
      return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
    }

    const parsed = await parseRequest(confluenceDeleteCommentContract, request, {})
    if (!parsed.success) return parsed.response

    const { domain, accessToken, cloudId: providedCloudId, commentId } = parsed.data.body

    const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))

    const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
    if (!cloudIdValidation.isValid) {
      return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
    }

    const apiBase = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2`

    // Detect comment type with a non-destructive GET so a 404 from a prior
    // deletion isn't masked by a second DELETE attempt against the wrong endpoint.
    let commentEndpoint = 'footer-comments'
    let detectResponse = await fetch(`${apiBase}/footer-comments/${commentId}`, {
      headers: {
        Accept: 'application/json',
        Authorization: `Bearer ${accessToken}`,
      },
    })

    if (detectResponse.status === 404) {
      commentEndpoint = 'inline-comments'
      detectResponse = await fetch(`${apiBase}/inline-comments/${commentId}`, {
        headers: {
          Accept: 'application/json',
          Authorization: `Bearer ${accessToken}`,
        },
      })
    }

    if (!detectResponse.ok) {
      const errorText = await detectResponse.text()
      logger.error('Confluence API error response:', {
        status: detectResponse.status,
        statusText: detectResponse.statusText,
        error: errorText,
      })
      return NextResponse.json(
        {
          error: parseAtlassianErrorMessage(
            detectResponse.status,
            detectResponse.statusText,
            errorText
          ),
        },
        { status: detectResponse.status }
      )
    }

    const response = await fetch(`${apiBase}/${commentEndpoint}/${commentId}`, {
      method: 'DELETE',
      headers: {
        Accept: 'application/json',
        Authorization: `Bearer ${accessToken}`,
      },
    })

    if (!response.ok) {
      const errorText = await response.text()
      logger.error('Confluence API error response:', {
        status: response.status,
        statusText: response.statusText,
        error: errorText,
      })
      return NextResponse.json(
        { error: parseAtlassianErrorMessage(response.status, response.statusText, errorText) },
        { status: response.status }
      )
    }

    return NextResponse.json({ commentId, deleted: true })
  } catch (error) {
    logger.error('Error deleting Confluence comment:', error)
    return NextResponse.json(
      { error: (error as Error).message || 'Internal server error' },
      { status: 500 }
    )
  }
})
