import { NextRequest, NextResponse } from 'next/server';
import { listA2PRegistrations, createA2PRegistration, getA2PStats } from '@/lib/db';
import { generateId } from '@/lib/utils';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const status = searchParams.get('status') || undefined;
    const limit = parseInt(searchParams.get('limit') || '50', 10);
    const offset = parseInt(searchParams.get('offset') || '0', 10);
    const includeStats = searchParams.get('stats') === 'true';

    const registrations = listA2PRegistrations({
      status,
      limit: Math.min(limit, 200),
      offset: Math.max(offset, 0),
    });

    // Parse JSON fields for the response
    const parsed = registrations.map((r) => ({
      ...r,
      input: JSON.parse(r.input_json),
      sidChain: JSON.parse(r.sid_chain_json || '{}'),
    }));

    const response: Record<string, unknown> = {
      registrations: parsed,
      count: parsed.length,
    };

    if (includeStats) {
      response.stats = getA2PStats();
    }

    return NextResponse.json(response);
  } catch (error) {
    console.error('GET /api/a2p error:', error);
    return NextResponse.json(
      { error: 'Failed to fetch A2P registrations' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();

    if (!body.business?.businessName) {
      return NextResponse.json(
        { error: 'Business name is required' },
        { status: 400 }
      );
    }

    const id = generateId();
    const inputJson = JSON.stringify(body);

    createA2PRegistration({
      id,
      business_name: body.business.businessName,
      status: 'pending',
      input_json: inputJson,
    });

    return NextResponse.json({
      id,
      status: 'pending',
      message: 'A2P registration created successfully. Submission will begin shortly.',
    }, { status: 201 });
  } catch (error) {
    console.error('POST /api/a2p error:', error);
    return NextResponse.json(
      { error: 'Failed to create A2P registration' },
      { status: 500 }
    );
  }
}
