import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'

/**
 * vCard Export API
 *
 * GET /api/team/[slug]/vcard - Generiert vCard (VCF) für ein Team-Mitglied
 *
 * Query-Parameter:
 * - tenant (required): Tenant ID
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ slug: string }> }
) {
  try {
    const { slug } = await params
    const { searchParams } = new URL(request.url)

    // Required: Tenant
    const tenantId = searchParams.get('tenant')
    if (!tenantId) {
      return NextResponse.json({ error: 'tenant parameter is required' }, { status: 400 })
    }

    const payload = await getPayload({ config })

    // Find team member
    const result = await payload.find({
      collection: 'team',
      where: {
        tenant: { equals: parseInt(tenantId) },
        slug: { equals: slug },
        isActive: { equals: true },
      },
      depth: 1,
      limit: 1,
    })

    if (result.docs.length === 0) {
      return NextResponse.json({ error: 'Team member not found' }, { status: 404 })
    }

    const member = result.docs[0]

    // Check if vCard export is allowed
    if (member.allowVCard === false) {
      return NextResponse.json({ error: 'vCard export not allowed for this member' }, { status: 403 })
    }

    // Generate vCard 3.0
    const vcard = generateVCard(member as TeamMember)

    // Return as downloadable file
    const filename = `${member.slug || member.name?.toLowerCase().replace(/\s+/g, '-')}.vcf`

    return new NextResponse(vcard, {
      status: 200,
      headers: {
        'Content-Type': 'text/vcard; charset=utf-8',
        'Content-Disposition': `attachment; filename="${filename}"`,
      },
    })
  } catch (error) {
    console.error('vCard API error:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

interface TeamMember {
  name?: string
  role?: string
  department?: string
  email?: string
  phone?: string
  showContactInfo?: boolean
  image?: { url?: string } | number
  socialLinks?: Array<{ platform?: string; url?: string }>
  qualifications?: Array<{ title?: string }>
  specializations?: Array<{ title?: string }>
  languages?: Array<{ language?: string; level?: string }>
  bioShort?: string
}

function generateVCard(member: TeamMember): string {
  const lines: string[] = []

  // vCard header
  lines.push('BEGIN:VCARD')
  lines.push('VERSION:3.0')

  // Name
  if (member.name) {
    const nameParts = member.name.split(' ')
    const lastName = nameParts.pop() || ''
    const firstName = nameParts.join(' ')
    lines.push(`N:${escapeVCard(lastName)};${escapeVCard(firstName)};;;`)
    lines.push(`FN:${escapeVCard(member.name)}`)
  }

  // Organization & Title
  if (member.role) {
    lines.push(`TITLE:${escapeVCard(member.role)}`)
  }
  if (member.department) {
    lines.push(`ORG:;${escapeVCard(member.department)}`)
  }

  // Contact info (only if allowed)
  if (member.showContactInfo) {
    if (member.email) {
      lines.push(`EMAIL;TYPE=WORK:${member.email}`)
    }
    if (member.phone) {
      lines.push(`TEL;TYPE=WORK:${member.phone}`)
    }
  }

  // Photo URL (if available)
  if (member.image && typeof member.image === 'object' && member.image.url) {
    lines.push(`PHOTO;VALUE=URI:${member.image.url}`)
  }

  // Social Links as URLs
  if (Array.isArray(member.socialLinks)) {
    member.socialLinks.forEach((link, index) => {
      if (link.url) {
        const label = link.platform?.toUpperCase() || `SOCIAL${index + 1}`
        lines.push(`URL;TYPE=${label}:${link.url}`)
      }
    })
  }

  // Note with bio and qualifications
  const notes: string[] = []
  if (member.bioShort) {
    notes.push(member.bioShort)
  }
  if (Array.isArray(member.qualifications) && member.qualifications.length > 0) {
    const quals = member.qualifications.map((q) => q.title).filter(Boolean).join(', ')
    if (quals) {
      notes.push(`Qualifikationen: ${quals}`)
    }
  }
  if (Array.isArray(member.specializations) && member.specializations.length > 0) {
    const specs = member.specializations.map((s) => s.title).filter(Boolean).join(', ')
    if (specs) {
      notes.push(`Fachgebiete: ${specs}`)
    }
  }
  if (Array.isArray(member.languages) && member.languages.length > 0) {
    const langs = member.languages.map((l) => l.language).filter(Boolean).join(', ')
    if (langs) {
      notes.push(`Sprachen: ${langs}`)
    }
  }
  if (notes.length > 0) {
    lines.push(`NOTE:${escapeVCard(notes.join('\\n'))}`)
  }

  // Categories (specializations as tags)
  if (Array.isArray(member.specializations) && member.specializations.length > 0) {
    const categories = member.specializations.map((s) => s.title).filter(Boolean).join(',')
    if (categories) {
      lines.push(`CATEGORIES:${escapeVCard(categories)}`)
    }
  }

  // Production ID and revision
  lines.push(`PRODID:-//Payload CMS//Team vCard//DE`)
  lines.push(`REV:${new Date().toISOString().replace(/[-:]/g, '').split('.')[0]}Z`)

  // vCard footer
  lines.push('END:VCARD')

  return lines.join('\r\n')
}

function escapeVCard(text: string): string {
  if (!text) return ''
  return text
    .replace(/\\/g, '\\\\')
    .replace(/;/g, '\\;')
    .replace(/,/g, '\\,')
    .replace(/\n/g, '\\n')
}
