import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/auth';
import {
  pgAcquireSupplierPaymentLock,
  pgGetSupplierPaymentLockByBeneficiary,
  pgReleaseSupplierPaymentLock,
} from '@/lib/postgres/data-access';

function getLockKey(supplierId: string) {
  return `cn:${supplierId}`;
}

export async function POST(req: NextRequest) {
  const session = await getSession();
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const body = await req.json();
    const action = String(body?.action || '').trim();
    const supplierId = String(body?.supplierId || '').trim();

    if (!action || !supplierId) {
      return NextResponse.json({ error: 'action and supplierId are required' }, { status: 400 });
    }

    const userId = session.user.id;
    const userName = session.user.name || session.user.username || 'User';
    const lockKey = getLockKey(supplierId);

    if (action === 'acquire') {
      const result = await pgAcquireSupplierPaymentLock(lockKey, userId, userName);
      return NextResponse.json(result, { status: result.success ? 200 : 409 });
    }

    if (action === 'release') {
      await pgReleaseSupplierPaymentLock(lockKey, userId);
      return NextResponse.json({ success: true }, { status: 200 });
    }

    if (action === 'status') {
      const lock = await pgGetSupplierPaymentLockByBeneficiary(lockKey);
      if (!lock) {
        return NextResponse.json({ locked: false, success: true }, { status: 200 });
      }

      const lockedByMe = lock.userId === userId;
      return NextResponse.json({
        locked: true,
        lockedByMe,
        lockedBy: lock.userName,
        success: lockedByMe,
      }, { status: lockedByMe ? 200 : 409 });
    }

    return NextResponse.json({ error: 'Unsupported action' }, { status: 400 });
  } catch (error: any) {
    return NextResponse.json({ error: error?.message || 'Lock operation failed' }, { status: 500 });
  }
}
