import { NextRequest, NextResponse } from 'next/server';
import { AuthError, requireHRD } from '@/lib/auth/session';
import { listEmployeeDirectoryForOrganization } from '@/features/employee-directory/server/employee-directory-data';

export async function GET(request: NextRequest) {
  try {
    const { organization } = await requireHRD();
    const { searchParams } = request.nextUrl;
    const result = await listEmployeeDirectoryForOrganization({
      organizationId: organization.id,
      filters: {
        page: Number(searchParams.get('page') ?? 1),
        limit: Number(searchParams.get('limit') ?? 10),
        search: searchParams.get('search') ?? undefined,
        company: searchParams.get('company') ?? undefined,
        department: searchParams.get('department') ?? undefined,
        position: searchParams.get('position') ?? undefined,
        status: searchParams.get('status') ?? undefined,
        sort: searchParams.get('sort') ?? undefined
      }
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Employee directory loaded successfully',
      total_employees: result.total,
      offset: result.offset,
      limit: result.limit,
      employees: result.employees,
      options: result.options
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: 'Unable to load employee directory' }, { status: 500 });
  }
}
