import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getSession, isServerAdmin } from '@/lib/auth'
import bcrypt from 'bcryptjs'
import crypto from 'crypto'
import { sendEmail, getSmtpConfig } from '@/lib/email'

function generateTempPassword(): string {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'
  let pw = ''
  for (let i = 0; i < 10; i++) pw += chars[crypto.randomInt(chars.length)]
  return pw
}

// Create a NEW user and add as member to tenant
export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    const user = await getSession()
    if (!user || !isServerAdmin(user.role)) {
      return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 403 })
    }

    const { name, email, role } = await req.json()
    if (!name || !email) {
      return NextResponse.json({ error: 'Name und E-Mail sind erforderlich' }, { status: 400 })
    }

    // Check tenant user limit
    const tenant = await (prisma as any).tenant.findUnique({
      where: { id: params.id },
      include: { _count: { select: { memberships: true } } },
    })
    if (!tenant) {
      return NextResponse.json({ error: 'Mandant nicht gefunden' }, { status: 404 })
    }
    // User limit removed — no restriction on number of users

    // Check if user with this email already exists
    const existingUser = await (prisma as any).user.findUnique({ where: { email: email.toLowerCase() } })
    if (existingUser) {
      // Check if already member of this tenant
      const existingMembership = await (prisma as any).tenantMembership.findUnique({
        where: { userId_tenantId: { userId: existingUser.id, tenantId: params.id } },
      })
      if (existingMembership) {
        return NextResponse.json({ error: 'Ein Benutzer mit dieser E-Mail ist bereits Mitglied dieses Mandanten.' }, { status: 400 })
      }
      return NextResponse.json({ error: 'Ein Benutzer mit dieser E-Mail existiert bereits im System. Bitte verwenden Sie eine andere E-Mail-Adresse.' }, { status: 400 })
    }

    // Generate temp password
    const tempPassword = generateTempPassword()
    const hashedPassword = await bcrypt.hash(tempPassword, 12)

    // Create user + membership in transaction
    const result = await (prisma as any).$transaction(async (tx: any) => {
      const newUser = await tx.user.create({
        data: {
          email: email.toLowerCase(),
          name,
          password: hashedPassword,
          role: role || 'OPERATOR',
        },
      })
      const membership = await tx.tenantMembership.create({
        data: {
          userId: newUser.id,
          tenantId: params.id,
          role: role || 'OPERATOR',
        },
        include: { user: { select: { id: true, email: true, name: true, role: true } } },
      })
      return { user: newUser, membership }
    })

    // Send welcome email (best effort)
    let emailSent = false
    try {
      const smtpConfig = await getSmtpConfig()
      if (smtpConfig) {
        const appUrl = process.env.NEXT_PUBLIC_APP_URL || process.env.NEXTAUTH_URL || 'https://app.lageplan.ch'
        const html = `
          <div style="font-family:sans-serif;max-width:600px;margin:0 auto;">
            <div style="background:#dc2626;color:white;padding:20px 24px;border-radius:12px 12px 0 0;">
              <h1 style="margin:0;font-size:22px;">Willkommen bei Lageplan</h1>
            </div>
            <div style="border:1px solid #e5e7eb;border-top:none;padding:24px;border-radius:0 0 12px 12px;">
              <p>Hallo <strong>${name}</strong>,</p>
              <p>Sie wurden als Benutzer für <strong>${tenant.name}</strong> eingerichtet.</p>
              <div style="background:#f3f4f6;border-radius:8px;padding:16px;margin:20px 0;">
                <p style="margin:0 0 8px;font-size:14px;color:#6b7280;">Ihre Zugangsdaten:</p>
                <table style="width:100%;">
                  <tr><td style="padding:4px 0;font-weight:bold;width:100px;">E-Mail:</td><td>${email.toLowerCase()}</td></tr>
                  <tr><td style="padding:4px 0;font-weight:bold;">Passwort:</td><td style="font-family:monospace;font-size:16px;letter-spacing:1px;">${tempPassword}</td></tr>
                </table>
              </div>
              <p style="color:#dc2626;font-weight:bold;font-size:14px;">Bitte ändern Sie Ihr Passwort nach der ersten Anmeldung.</p>
              <a href="${appUrl}/login" style="display:inline-block;background:#dc2626;color:white;padding:12px 24px;border-radius:8px;text-decoration:none;font-weight:bold;margin-top:12px;">
                Jetzt anmelden
              </a>
              <hr style="border:none;border-top:1px solid #e5e7eb;margin:24px 0;" />
              <p style="font-size:12px;color:#9ca3af;">Diese E-Mail wurde automatisch von Lageplan gesendet. Gehostet in der Schweiz.</p>
            </div>
          </div>
        `
        await sendEmail(email.toLowerCase(), `Willkommen bei Lageplan — Ihre Zugangsdaten für ${tenant.name}`, html)
        emailSent = true
      }
    } catch (e) {
      console.error('Welcome email failed:', e)
    }

    return NextResponse.json({
      membership: result.membership,
      tempPassword,
      emailSent,
    }, { status: 201 })
  } catch (error) {
    console.error('Error creating member:', error)
    return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
  }
}

// Remove a user from a tenant (and delete the user)
export async function DELETE(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    const user = await getSession()
    if (!user || !isServerAdmin(user.role)) {
      return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 403 })
    }

    const { searchParams } = new URL(req.url)
    const membershipId = searchParams.get('membershipId')
    const deleteUser = searchParams.get('deleteUser') === 'true'
    if (!membershipId) {
      return NextResponse.json({ error: 'membershipId erforderlich' }, { status: 400 })
    }

    // Get the membership to find the userId
    const membership = await (prisma as any).tenantMembership.findUnique({
      where: { id: membershipId },
    })

    // Delete membership
    await (prisma as any).tenantMembership.delete({ where: { id: membershipId } })

    // Optionally delete the user too (if they have no other memberships)
    if (deleteUser && membership) {
      const otherMemberships = await (prisma as any).tenantMembership.count({
        where: { userId: membership.userId },
      })
      if (otherMemberships === 0) {
        // Reassign projects to tenant admin before deleting
        const adminMembership = await (prisma as any).tenantMembership.findFirst({
          where: {
            tenantId: params.id,
            userId: { not: membership.userId },
            role: 'TENANT_ADMIN',
          },
        })
        const newOwnerId = adminMembership?.userId || user.id
        await (prisma as any).project.updateMany({
          where: { ownerId: membership.userId },
          data: { ownerId: newOwnerId },
        })
        await (prisma as any).user.delete({ where: { id: membership.userId } })
      }
    }

    return NextResponse.json({ success: true })
  } catch (error: any) {
    console.error('Error removing member:', error)
    const msg = error?.code === 'P2003'
      ? 'Benutzer kann nicht entfernt werden — es gibt noch abhängige Daten.'
      : 'Interner Fehler'
    return NextResponse.json({ error: msg }, { status: 500 })
  }
}
