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

const HEARTBEAT_TIMEOUT_MS = 2 * 60 * 1000 // 2 minutes

function isEditingExpired(heartbeat: Date | null): boolean {
  if (!heartbeat) return true
  return Date.now() - new Date(heartbeat).getTime() > HEARTBEAT_TIMEOUT_MS
}

// GET: Check editing status of a project
export async function GET(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const user = await getSession()
    if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })

    const sessionId = req.nextUrl.searchParams.get('sessionId') || ''

    const project = await (prisma as any).project.findUnique({
      where: { id: params.id },
      select: {
        id: true,
        editingById: true,
        editingUserName: true,
        editingSessionId: true,
        editingStartedAt: true,
        editingHeartbeat: true,
        isLocked: true,
      },
    })

    if (!project) {
      return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
    }

    // Auto-release if heartbeat expired
    if (project.editingById && isEditingExpired(project.editingHeartbeat)) {
      await (prisma as any).project.update({
        where: { id: params.id },
        data: {
          editingById: null,
          editingUserName: null,
          editingSessionId: null,
          editingStartedAt: null,
          editingHeartbeat: null,
        },
      })
      return NextResponse.json({
        editing: false,
        editingBy: null,
        isMe: false,
        isLocked: project.isLocked,
      })
    }

    // isMe is true only if sessionId matches (same tab/device)
    const isMe = !!sessionId && project.editingSessionId === sessionId

    return NextResponse.json({
      editing: !!project.editingById,
      editingBy: project.editingById ? {
        id: project.editingById,
        name: project.editingUserName,
        since: project.editingStartedAt,
      } : null,
      isMe,
      isLocked: project.isLocked,
    })
  } catch (error) {
    console.error('Error checking editing status:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}

// POST: Start editing / heartbeat / stop editing
export async function POST(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const user = await getSession()
    if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })

    const body = await req.json()
    const { action, sessionId } = body // 'start', 'heartbeat', 'stop'

    const project = await (prisma as any).project.findUnique({
      where: { id: params.id },
      select: {
        id: true,
        editingById: true,
        editingSessionId: true,
        editingHeartbeat: true,
        isLocked: true,
        tenantId: true,
      },
    })

    if (!project) {
      return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
    }

    if (action === 'start') {
      if (!sessionId) {
        return NextResponse.json({ error: 'sessionId fehlt' }, { status: 400 })
      }
      // Check if another session is editing (and heartbeat not expired)
      if (project.editingSessionId && project.editingSessionId !== sessionId && !isEditingExpired(project.editingHeartbeat)) {
        return NextResponse.json({
          error: 'Projekt wird gerade von jemand anderem bearbeitet',
          editingBy: project.editingById,
        }, { status: 409 })
      }

      // Start editing
      await (prisma as any).project.update({
        where: { id: params.id },
        data: {
          editingById: user.id,
          editingUserName: user.name,
          editingSessionId: sessionId,
          editingStartedAt: new Date(),
          editingHeartbeat: new Date(),
        },
      })

      return NextResponse.json({ success: true, action: 'started' })
    }

    if (action === 'heartbeat') {
      // Only the current session can send heartbeats
      if (project.editingSessionId !== sessionId) {
        return NextResponse.json({ error: 'Sie sind nicht der aktuelle Bearbeiter' }, { status: 403 })
      }

      await (prisma as any).project.update({
        where: { id: params.id },
        data: { editingHeartbeat: new Date() },
      })

      return NextResponse.json({ success: true, action: 'heartbeat' })
    }

    if (action === 'stop') {
      // Only the current session or a SERVER_ADMIN can stop editing
      if (project.editingSessionId !== sessionId && user.role !== 'SERVER_ADMIN') {
        return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
      }

      await (prisma as any).project.update({
        where: { id: params.id },
        data: {
          editingById: null,
          editingUserName: null,
          editingSessionId: null,
          editingStartedAt: null,
          editingHeartbeat: null,
        },
      })

      return NextResponse.json({ success: true, action: 'stopped' })
    }

    return NextResponse.json({ error: 'Ungültige Aktion' }, { status: 400 })
  } catch (error) {
    console.error('Error managing editing lock:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
