import { NextRequest, NextResponse } from 'next/server';
import { verifySession } from '@/lib/auth';

import {
  acquireDocumentLock,
  checkDocumentLock,
  releaseDocumentLock,
  cleanupExpiredLocks,
  getSettingsMap,
} from '@/lib/postgres/repositories';

export async function POST(request: NextRequest) {
  try {
    const { action, documentType, documentId } = await request.json();
    const session = await verifySession();

    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const settings = await getSettingsMap();
    const showEditingMessageToUser = settings?.showEditingMessageToUser !== false && settings?.showEditingMessageToUser !== 'false';

    if (action === 'acquire') {
      const result = await acquireDocumentLock(
        documentType,
        documentId,
        session.user.id,
        session.user.name || 'Unknown User'
      );

      if (!result.success) {
        return NextResponse.json({
          success: false,
          showEditingMessageToUser,
          lockedBy: {
            userName: result.lockedBy?.userName,
            lockedAt: result.lockedBy?.lockedAt,
          },
        });
      }

      return NextResponse.json({ success: true, lock: result.lock, showEditingMessageToUser });
    }

    if (action === 'check') {
      const lock = await checkDocumentLock(documentType, documentId);
      return NextResponse.json({
        isLocked: !!lock,
        showEditingMessageToUser,
        lock: lock
          ? {
              ...lock,
              user_name: (lock as any).userName,
              locked_at: (lock as any).lockedAt,
            }
          : null,
      });
    }

    if (action === 'release') {
      const released = await releaseDocumentLock(documentType, documentId, session.user.id);
      return NextResponse.json({ success: released, showEditingMessageToUser });
    }

    if (action === 'cleanup') {
      const cleaned = await cleanupExpiredLocks();
      return NextResponse.json({ success: true, cleaned, showEditingMessageToUser });
    }

    return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
  } catch (error) {
    console.error('Document lock error:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Lock operation failed' },
      { status: 500 }
    );
  }
}
