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 { pgListBackgroundJobLogs } from '@/lib/postgres/scheduler';

export async function GET(request: NextRequest) {
  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 { searchParams } = new URL(request.url);
    const jobId = searchParams.get('jobId') || undefined;
    const status = searchParams.get('status') as 'pending' | 'running' | 'success' | 'failed' | 'retry' | null;
    const limitParam = Number(searchParams.get('limit') || '100');
    const limit = Number.isFinite(limitParam) ? limitParam : 100;

    const logs = await pgListBackgroundJobLogs({
      jobId,
      status: status || undefined,
      limit,
    });

    return NextResponse.json({ items: logs, total: logs.length }, { status: 200 });
  } catch (error) {
    console.error('Error fetching scheduler logs:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
