import type { APIRoute } from 'astro';
import { TerritoryManagerAuth } from '../../../../lib/territory-manager-auth';
import { territoryManagerAPI } from '../../../../lib/territory-manager-api';

export const POST: APIRoute = async ({ request: _request }) => {
  try {
    // Check if user is authenticated as territory manager
    const territoryManager = await TerritoryManagerAuth.getCurrentTerritoryManager();
    if (!territoryManager) {
      return new Response(JSON.stringify({ error: 'Not authenticated as territory manager' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Get all unread notifications
    const notifications = await territoryManagerAPI.getNotifications(territoryManager.id);
    const unreadNotifications = notifications.filter(n => !n.read);

    // Mark all as read
    await Promise.all(
      unreadNotifications.map(n => territoryManagerAPI.markNotificationAsRead(n.id))
    );

    return new Response(JSON.stringify({ 
      success: true, 
      markedCount: unreadNotifications.length 
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

  } catch (_error) {
    console.error('Error marking notifications as read:', _error);
    return new Response(JSON.stringify({ error: 'Internal server error' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};