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

// POST: Tenant self-deletion — TENANT_ADMIN deletes own organization with all data
export async function POST(req: NextRequest) {
  try {
    const user = await getSession()
    if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })

    const body = await req.json()
    const { confirmText } = body

    if (!user.tenantId) {
      return NextResponse.json({ error: 'Kein Mandant zugeordnet' }, { status: 400 })
    }

    // Verify user is TENANT_ADMIN
    if (user.role !== 'TENANT_ADMIN' && user.role !== 'SERVER_ADMIN') {
      return NextResponse.json({ error: 'Nur der Organisations-Administrator kann die Organisation löschen' }, { status: 403 })
    }

    // Get tenant info for confirmation
    const tenant = await (prisma as any).tenant.findUnique({
      where: { id: user.tenantId },
      select: { id: true, name: true, slug: true },
    })
    if (!tenant) {
      return NextResponse.json({ error: 'Mandant nicht gefunden' }, { status: 404 })
    }

    // Require confirmation text to match tenant name
    if (confirmText !== tenant.name) {
      return NextResponse.json({ error: `Bitte geben Sie "${tenant.name}" zur Bestätigung ein` }, { status: 400 })
    }

    console.log(`[Tenant Delete] User ${user.id} deleting tenant ${tenant.id} (${tenant.name})`)

    // Delete everything in order (respecting foreign keys)
    // 1. Rapports
    await (prisma as any).rapport.deleteMany({ where: { tenantId: tenant.id } })

    // 2. Journal entries (via projects)
    const projectIds = await (prisma as any).project.findMany({
      where: { tenantId: tenant.id },
      select: { id: true },
    })
    const pIds = projectIds.map((p: any) => p.id)
    if (pIds.length > 0) {
      await (prisma as any).journalEntry.deleteMany({ where: { projectId: { in: pIds } } })
      await (prisma as any).journalCheckItem.deleteMany({ where: { projectId: { in: pIds } } })
      await (prisma as any).journalPendenz.deleteMany({ where: { projectId: { in: pIds } } })
    }

    // 3. Projects
    await (prisma as any).project.deleteMany({ where: { tenantId: tenant.id } })

    // 4. Icon assets & categories
    await (prisma as any).iconAsset.deleteMany({ where: { tenantId: tenant.id } })
    await (prisma as any).iconCategory.deleteMany({ where: { tenantId: tenant.id } })

    // 5. Hose types, check templates, dictionary entries
    try { await (prisma as any).hoseType.deleteMany({ where: { tenantId: tenant.id } }) } catch {}
    try { await (prisma as any).journalCheckTemplate.deleteMany({ where: { tenantId: tenant.id } }) } catch {}
    try { await (prisma as any).dictionaryEntry.deleteMany({ where: { tenantId: tenant.id } }) } catch {}
    try { await (prisma as any).upgradeRequest.deleteMany({ where: { tenantId: tenant.id } }) } catch {}

    // 6. Get all user IDs from memberships
    const memberships = await (prisma as any).tenantMembership.findMany({
      where: { tenantId: tenant.id },
      select: { userId: true },
    })
    const userIds = memberships.map((m: any) => m.userId)

    // 7. Delete memberships
    await (prisma as any).tenantMembership.deleteMany({ where: { tenantId: tenant.id } })

    // 8. Delete users that have no other memberships
    for (const uid of userIds) {
      const otherMemberships = await (prisma as any).tenantMembership.count({
        where: { userId: uid },
      })
      if (otherMemberships === 0) {
        try {
          await (prisma as any).user.delete({ where: { id: uid } })
        } catch (e) {
          console.warn(`[Tenant Delete] Could not delete user ${uid}:`, e)
        }
      }
    }

    // 9. Delete tenant itself
    await (prisma as any).tenant.delete({ where: { id: tenant.id } })

    console.log(`[Tenant Delete] Tenant ${tenant.name} (${tenant.id}) fully deleted`)

    return NextResponse.json({ success: true, message: 'Organisation und alle Daten wurden gelöscht' })
  } catch (error: any) {
    console.error('[Tenant Delete] Error:', error?.message || error)
    return NextResponse.json({ error: error?.message || 'Löschung fehlgeschlagen' }, { status: 500 })
  }
}
