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 }) => {
  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 optional event type from request body
    const body = await request.json().catch(() => ({}));
    const { eventType } = body;

    // Generate referral link
    const referralLink = await territoryManagerAPI.generateReferralLink(territoryManager.id, eventType);

    return new Response(JSON.stringify(referralLink), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

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