import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getSession } from '@/lib/auth'

async function getTenantId() {
  const user = await getSession()
  if (!user) return { error: 'Nicht autorisiert', status: 401 }
  if (user.role !== 'TENANT_ADMIN' && user.role !== 'SERVER_ADMIN') {
    return { error: 'Keine Berechtigung', status: 403 }
  }
  if (!user.tenantId) return { error: 'Kein Mandant zugeordnet', status: 400 }
  return { tenantId: user.tenantId }
}

/**
 * POST /api/templates/import
 * Importiert Symbole aus einem Template-Paket als TenantSymbols.
 *
 * Body:
 *   {
 *     packageId: "feuerwehr-ch",
 *     symbolIds?: ["id1", "id2"],  // optional: nur ausgewählte, sonst alle
 *   }
 *
 * Response:
 *   { imported: [{ tenantSymbolId, name, categoryId }] }
 */
export async function POST(req: NextRequest) {
  try {
    const auth = await getTenantId()
    if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
    const { tenantId } = auth

    const { packageId, symbolIds } = await req.json()
    if (!packageId) return NextResponse.json({ error: 'packageId erforderlich' }, { status: 400 })

    // 1. Fetch templates to import
    const where: any = { packageId }
    if (symbolIds && Array.isArray(symbolIds) && symbolIds.length > 0) {
      where.id = { in: symbolIds }
    }

    const templates = await (prisma as any).symbolTemplate.findMany({ where })
    if (templates.length === 0) {
      return NextResponse.json({ error: 'Keine Symbole im Paket gefunden' }, { status: 404 })
    }

    // 2. Ensure default category exists for each template category
    const categoryMap = new Map<string, string>() // categoryName -> TenantCategory.id
    const uniqueCategoryNames: string[] = [...new Set<string>(templates.map((t: any) => t.categoryName as string))]

    for (const catName of uniqueCategoryNames) {
      let tenantCat = await (prisma as any).tenantCategory.findFirst({
        where: { tenantId, name: catName },
      })
      if (!tenantCat) {
        tenantCat = await (prisma as any).tenantCategory.create({
          data: { tenantId, name: catName, sortOrder: 0 },
        })
      }
      categoryMap.set(catName, tenantCat.id)
    }

    // 3. Get current max sortOrder for tenant
    const maxSortAgg = await (prisma as any).tenantSymbol.aggregate({
      where: { tenantId },
      _max: { sortOrder: true },
    })
    let currentSort = (maxSortAgg._max.sortOrder ?? -1) + 1

    // 4. Import each template as TenantSymbol
    const imported: Array<{
      tenantSymbolId: string
      name: string
      categoryId: string
      svgPath: string
    }> = []

    for (const tpl of templates) {
      const categoryId = categoryMap.get(tpl.categoryName)
      if (!categoryId) continue

      // Check if already exists (same name + svgPath in this tenant)
      const existing = await (prisma as any).tenantSymbol.findFirst({
        where: { tenantId, name: tpl.name, svgPath: tpl.svgPath },
      })
      if (existing) {
        // Skip already imported symbols
        continue
      }

      const tenantSymbol = await (prisma as any).tenantSymbol.create({
        data: {
          tenantId,
          categoryId,
          name: tpl.name,
          svgPath: tpl.svgPath,
          sortOrder: currentSort++,
          isUploaded: false,
        },
      })

      imported.push({
        tenantSymbolId: tenantSymbol.id,
        name: tenantSymbol.name,
        categoryId: tenantSymbol.categoryId,
        svgPath: tenantSymbol.svgPath,
      })
    }

    return NextResponse.json({ imported, count: imported.length })
  } catch (error) {
    console.error('Error importing templates:', error)
    return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
  }
}
