import { NextRequest, NextResponse } from 'next/server';

const API_URL = 'http://aggios-backend:8080';

export async function GET(request: NextRequest) {
    try {
        const token = request.headers.get('authorization') || '';
        const subdomain = request.headers.get('x-tenant-subdomain') || request.headers.get('host')?.split('.')[0] || '';

        console.log('[API Route] GET /api/crm/customers - subdomain:', subdomain);

        const response = await fetch(`${API_URL}/api/crm/customers`, {
            headers: {
                'Authorization': token,
                'X-Tenant-Subdomain': subdomain,
                'Content-Type': 'application/json',
            },
        });

        const data = await response.json();

        if (!response.ok) {
            return NextResponse.json(data, { status: response.status });
        }

        return NextResponse.json(data);
    } catch (error) {
        console.error('[API Route] Error fetching customers:', error);
        return NextResponse.json(
            { error: 'Failed to fetch customers', details: String(error) },
            { status: 500 }
        );
    }
}

export async function POST(request: NextRequest) {
    try {
        const token = request.headers.get('authorization') || '';
        const subdomain = request.headers.get('x-tenant-subdomain') || request.headers.get('host')?.split('.')[0] || '';
        const body = await request.json();

        const response = await fetch(`${API_URL}/api/crm/customers`, {
            method: 'POST',
            headers: {
                'Authorization': token,
                'X-Tenant-Subdomain': subdomain,
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(body),
        });

        const data = await response.json();

        if (!response.ok) {
            return NextResponse.json(data, { status: response.status });
        }

        return NextResponse.json(data);
    } catch (error) {
        console.error('Error creating customer:', error);
        return NextResponse.json(
            { error: 'Failed to create customer' },
            { status: 500 }
        );
    }
}
