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

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 { creditNoteId } = body;

    if (!creditNoteId) {
      return NextResponse.json(
        { error: 'creditNoteId is required' },
        { status: 400 }
      );
    }

    const creditNote = await pgPostPurchaseCreditNote(creditNoteId, session.user.id);

    return NextResponse.json(creditNote, { status: 200 });
  } catch (error: any) {
    if (error.message === 'CREDIT_NOTE_NOT_FOUND') {
      return NextResponse.json(
        { error: 'Credit note not found' },
        { status: 404 }
      );
    }

    if (error.message === 'CREDIT_NOTE_ALREADY_POSTED') {
      return NextResponse.json(
        { error: 'Credit note is already posted' },
        { status: 409 }
      );
    }

    console.error('Error posting credit note:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to post credit note' },
      { status: 500 }
    );
  }
}
