import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/auth';
import { hasEmployeePermission } from '@/lib/employee-permissions';
import { pgGetSettings } from '@/lib/postgres/data-access';
import { pgPostExpenseDocument } from '@/lib/postgres/expense-recurring';

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await getSession();
  const settings = await pgGetSettings();
  if (!session?.user || (!hasEmployeePermission(session.user, settings, 'admin.accounting') && !hasEmployeePermission(session.user, settings, 'admin.expense-recurring'))) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const { id } = await params;
    const body = await request.json().catch(() => ({}));

    const updated = await pgPostExpenseDocument(
      id,
      {
        id: String(session.user.id || ''),
        name: session.user.name || session.user.username || session.user.id,
      },
      body?.postingDate ? String(body.postingDate) : undefined
    );

    if (!updated) {
      return NextResponse.json({ error: 'Document not found' }, { status: 404 });
    }

    return NextResponse.json(updated, { status: 200 });
  } catch (error) {
    console.error('Error posting expense document:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
