import { NextRequest, NextResponse } from 'next/server';
import { listTrainingPolicyHistoryForOrganization } from '@/features/training-policy/server/training-policy-data';
import { AuthError, requirePermission } from '@/lib/auth/session';

type Params = { params: Promise<{ id: string }> };

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const { organization } = await requirePermission('training_policy:read');
    const { id } = await params;
    const policyId = Number(id);
    const history = await listTrainingPolicyHistoryForOrganization({
      organizationId: organization.id,
      policyId
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'โหลดประวัตินโยบายการอบรมเรียบร้อยแล้ว',
      history
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    console.error('GET /api/training-policies/[id]/history failed', error);
    return NextResponse.json({ message: 'ไม่สามารถโหลดประวัตินโยบายการอบรมได้' }, { status: 500 });
  }
}
