import { NextRequest, NextResponse } from 'next/server';
import { auditLogFilterSchema } from '@/features/audit-logs/schemas/audit-log';
import { listAuditLogsForOrganization } from '@/features/audit-logs/server/audit-log-data';
import { AuthError, requireIT } from '@/lib/auth/session';

export async function GET(request: NextRequest) {
  try {
    const { organization } = await requireIT();
    const filters = auditLogFilterSchema.parse({
      page: request.nextUrl.searchParams.get('page') ?? undefined,
      limit: request.nextUrl.searchParams.get('limit') ?? undefined,
      search: request.nextUrl.searchParams.get('search') ?? undefined,
      user: request.nextUrl.searchParams.get('user') ?? undefined,
      module: request.nextUrl.searchParams.get('module') ?? undefined,
      action: request.nextUrl.searchParams.get('action') ?? undefined,
      dateFrom: request.nextUrl.searchParams.get('dateFrom') ?? undefined,
      dateTo: request.nextUrl.searchParams.get('dateTo') ?? undefined,
      sort: request.nextUrl.searchParams.get('sort') ?? undefined
    });

    const result = await listAuditLogsForOrganization({
      organizationId: organization.id,
      filters
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'โหลดประวัติการใช้งานเรียบร้อยแล้ว',
      total_audit_logs: result.total,
      offset: result.offset,
      limit: result.limit,
      audit_logs: result.auditLogs
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: 'ไม่สามารถโหลดประวัติการใช้งานได้' }, { status: 500 });
  }
}
