import { NextRequest, NextResponse } from 'next/server';
import { markNotificationAsRead } from '@/features/notifications/server/notification-service';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

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

export async function PATCH(request: NextRequest, { params }: Params) {
  try {
    const { organization, session } = await requireOrganizationAccess();
    const { id } = await params;

    const updated = await markNotificationAsRead({
      organizationId: organization.id,
      notificationId: Number(id),
      actorUserId: session.user.id,
      request
    });

    if (!updated) {
      return NextResponse.json({ message: 'ไม่พบการแจ้งเตือน' }, { status: 404 });
    }

    return NextResponse.json({
      success: true,
      message: 'อ่านการแจ้งเตือนแล้ว'
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

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