import { NextRequest, NextResponse } from 'next/server'
import { isAuthError, requireUser } from '@/lib/auth/session'
import { deleteMemberCompletely } from '@/lib/invite/lifecycle'

/**
 * DELETE /api/invite/member/[id]
 * Hard-remove a team member — the [id] is the channel id.
 *
 * Only the channel's owner (the user who created the invitation) can remove
 * the member. The check is "im_channels.owner_user_id == currentUser.id",
 * with no role-based logic.
 *
 * Effect (irreversible):
 *   - stops the running adapter (host stops listening to this bot)
 *   - DELETE im_channels (CASCADE: channel_bindings,
 *     weixin_context_tokens, weixin_sync_cursors, im_pairing_requests)
 *   - DELETE workspaces (CASCADE: sessions, messages, workspace_members)
 *   - DELETE invitations
 *   - fs.rmSync(<projectRoot>/users/user-{id}/) — physical directory
 */
export async function DELETE(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  let user
  try {
    user = await requireUser()
  } catch (err) {
    if (isAuthError(err)) return err
    throw err
  }

  const { id: channelId } = await params
  const result = await deleteMemberCompletely(channelId, user.id)
  if (!result.deleted) {
    if (result.reason === 'not_found') {
      return NextResponse.json({ error: 'Channel not found' }, { status: 404 })
    }
    return NextResponse.json({ error: 'Not authorized to remove this member' }, { status: 403 })
  }

  return NextResponse.json({
    success: true,
    userDir: result.userDir,
    dirRemoved: result.dirRemoved,
    dirError: result.dirError,
  })
}
