import { NextResponse } from 'next/server';
import {
  canManageTrainingMatrix,
  getTrainingMatrixComplianceForOrganization
} from '@/features/training-matrix/server/training-matrix-data';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

export async function GET() {
  try {
    const { organization, membership } = await requireOrganizationAccess();

    if (!canManageTrainingMatrix(membership.role)) {
      return NextResponse.json({ message: 'Forbidden' }, { status: 403 });
    }

    const employees = await getTrainingMatrixComplianceForOrganization(organization.id);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Training compliance loaded successfully',
      employees
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

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