import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { listNotificationsForUser } from '@/features/notifications/server/notification-data';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

const notificationFilterSchema = z.object({
  page: z.coerce.number().int().min(1).default(1),
  limit: z.coerce.number().int().min(1).max(100).default(10),
  search: z.string().trim().optional(),
  status: z.enum(['all', 'unread', 'read']).default('all'),
  type: z
    .enum([
      'TRAINING_APPROVED',
      'TRAINING_REJECTED',
      'ANNOUNCEMENT_PUBLISHED',
      'IMPORT_COMPLETED',
      'MASTER_REVIEW_APPROVED',
      'MASTER_REVIEW_REJECTED',
      'SYSTEM'
    ])
    .optional()
});

export async function GET(request: NextRequest) {
  try {
    const { organization, session } = await requireOrganizationAccess();
    const filters = notificationFilterSchema.parse({
      page: request.nextUrl.searchParams.get('page') ?? undefined,
      limit: request.nextUrl.searchParams.get('limit') ?? undefined,
      search: request.nextUrl.searchParams.get('search') ?? undefined,
      status: request.nextUrl.searchParams.get('status') ?? undefined,
      type: request.nextUrl.searchParams.get('type') ?? undefined
    });

    const result = await listNotificationsForUser({
      organizationId: organization.id,
      userId: session.user.id,
      filters
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'โหลดการแจ้งเตือนเรียบร้อยแล้ว',
      total_notifications: result.total,
      unread_count: result.unreadCount,
      offset: result.offset,
      limit: result.limit,
      notifications: result.notifications
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: 'ไม่สามารถโหลดการแจ้งเตือนได้' }, { status: 500 });
  }
}
