import { createLogger } from '@sim/logger'
import { convert } from 'html-to-text'
import { type NextRequest, NextResponse } from 'next/server'
import { Resend } from 'resend'
import { mailSendContract } from '@/lib/api/contracts/tools/mail'
import { getValidationErrorMessage, parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'

export const dynamic = 'force-dynamic'

const logger = createLogger('MailSendAPI')

export const POST = withRouteHandler(async (request: NextRequest) => {
  const requestId = generateRequestId()

  try {
    const authResult = await checkInternalAuth(request, { requireWorkflowId: false })

    if (!authResult.success) {
      logger.warn(`[${requestId}] Unauthorized mail send attempt: ${authResult.error}`)
      return NextResponse.json(
        {
          success: false,
          message: authResult.error || 'Authentication required',
        },
        { status: 401 }
      )
    }

    logger.info(`[${requestId}] Authenticated mail request via ${authResult.authType}`, {
      userId: authResult.userId,
    })

    const parsed = await parseRequest(
      mailSendContract,
      request,
      {},
      {
        validationErrorResponse: (error) => {
          logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues })
          return NextResponse.json(
            {
              success: false,
              message: getValidationErrorMessage(error, 'Invalid request data'),
              errors: error.issues,
            },
            { status: 400 }
          )
        },
      }
    )
    if (!parsed.success) return parsed.response
    const validatedData = parsed.data.body

    logger.info(`[${requestId}] Sending email with user-provided Resend API key`, {
      to: validatedData.to,
      subject: validatedData.subject,
      bodyLength: validatedData.body.length,
      from: validatedData.fromAddress,
    })

    const resend = new Resend(validatedData.resendApiKey)

    const contentType = validatedData.contentType || 'text'
    const emailBase = {
      from: validatedData.fromAddress,
      to: validatedData.to,
      subject: validatedData.subject,
    }

    let emailData: Parameters<typeof resend.emails.send>[0]
    if (contentType === 'html') {
      emailData = {
        ...emailBase,
        html: validatedData.body,
        text: convert(validatedData.body, { wordwrap: false }),
      }
    } else {
      emailData = {
        ...emailBase,
        text: validatedData.body,
      }
    }

    if (validatedData.cc) {
      emailData.cc = validatedData.cc
    }

    if (validatedData.bcc) {
      emailData.bcc = validatedData.bcc
    }

    if (validatedData.replyTo) {
      emailData.replyTo = validatedData.replyTo
    }

    if (validatedData.scheduledAt) {
      emailData.scheduledAt = validatedData.scheduledAt
    }

    if (validatedData.tags) {
      const tagPairs = validatedData.tags.split(',').map((pair) => {
        const trimmed = pair.trim()
        const colonIndex = trimmed.indexOf(':')
        if (colonIndex === -1) return null
        const name = trimmed.substring(0, colonIndex).trim()
        const value = trimmed.substring(colonIndex + 1).trim()
        return { name, value: value || '' }
      })
      emailData.tags = tagPairs.filter(
        (tag): tag is { name: string; value: string } => tag !== null && !!tag.name
      )
    }

    const { data, error } = await resend.emails.send(emailData)

    if (error) {
      logger.error(`[${requestId}] Email sending failed:`, error)
      return NextResponse.json(
        {
          success: false,
          message: `Failed to send email: ${error.message || 'Unknown error'}`,
        },
        { status: 500 }
      )
    }

    const result = {
      success: true,
      message: 'Email sent successfully via Resend',
      data,
    }

    logger.info(`[${requestId}] Email send result`, {
      success: result.success,
      message: result.message,
    })

    return NextResponse.json(result)
  } catch (error) {
    logger.error(`[${requestId}] Error sending email via API:`, error)

    return NextResponse.json(
      {
        success: false,
        message: 'Internal server error while sending email',
        data: {},
      },
      { status: 500 }
    )
  }
})
