import { NextRequest, NextResponse } from 'next/server';
import { listNotificationHistory } from '@/features/foundation/notifications/server/service';
import { NOTIFICATION_CHANNELS, NOTIFICATION_DISPATCH_STATUSES } from '@/features/foundation/notifications/types';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

export async function GET(request: NextRequest) {
  try {
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.notificationViewHistory,
    });
    const { searchParams } = request.nextUrl;

    const page = Number(searchParams.get('page') ?? 1);
    const limit = Number(searchParams.get('limit') ?? 20);
    const channel = searchParams.get('channel');
    const status = searchParams.get('status');

    const result = await listNotificationHistory(organization.id, {
      page,
      limit,
      channel:
        channel && [...NOTIFICATION_CHANNELS, 'all'].includes(channel as never)
          ? (channel as (typeof NOTIFICATION_CHANNELS)[number] | 'all')
          : 'all',
      status:
        status && [...NOTIFICATION_DISPATCH_STATUSES, 'all'].includes(status as never)
          ? (status as (typeof NOTIFICATION_DISPATCH_STATUSES)[number] | 'all')
          : 'all',
      eventType: searchParams.get('eventType') ?? undefined,
      entityType: searchParams.get('entityType') ?? undefined,
      entityId: searchParams.get('entityId') ?? undefined,
      search: searchParams.get('search') ?? undefined,
    });

    return NextResponse.json(result);
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

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