import { NextRequest, NextResponse } from 'next/server';
import { getA2PRegistration, updateA2PRegistration, updateA2PStatus, deleteA2PRegistration } from '@/lib/db';

export async function GET(
  _request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const registration = getA2PRegistration(params.id);

    if (!registration) {
      return NextResponse.json(
        { error: 'Registration not found' },
        { status: 404 }
      );
    }

    return NextResponse.json({
      ...registration,
      input: JSON.parse(registration.input_json),
      sidChain: JSON.parse(registration.sid_chain_json || '{}'),
    });
  } catch (error) {
    console.error(`GET /api/a2p/${params.id} error:`, error);
    return NextResponse.json(
      { error: 'Failed to fetch registration' },
      { status: 500 }
    );
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const registration = getA2PRegistration(params.id);
    if (!registration) {
      return NextResponse.json(
        { error: 'Registration not found' },
        { status: 404 }
      );
    }

    const body = await request.json();

    // If updating the full input (for remediation), merge with existing
    if (body.input) {
      const existingInput = JSON.parse(registration.input_json);
      const mergedInput = { ...existingInput, ...body.input };
      updateA2PRegistration(params.id, {
        input_json: JSON.stringify(mergedInput),
        business_name: mergedInput.business?.businessName || registration.business_name,
      });
    }

    // If updating status
    if (body.status) {
      updateA2PStatus(params.id, body.status, body.failureReason);
    }

    // If updating other fields
    const directUpdates: Record<string, unknown> = {};
    if (body.landing_page_url !== undefined) directUpdates.landing_page_url = body.landing_page_url;
    if (body.privacy_policy_url !== undefined) directUpdates.privacy_policy_url = body.privacy_policy_url;
    if (body.terms_url !== undefined) directUpdates.terms_url = body.terms_url;
    if (body.brand_trust_score !== undefined) directUpdates.brand_trust_score = body.brand_trust_score;

    if (Object.keys(directUpdates).length > 0) {
      updateA2PRegistration(params.id, directUpdates as Parameters<typeof updateA2PRegistration>[1]);
    }

    const updated = getA2PRegistration(params.id);
    return NextResponse.json({
      ...updated,
      input: JSON.parse(updated!.input_json),
      sidChain: JSON.parse(updated!.sid_chain_json || '{}'),
    });
  } catch (error) {
    console.error(`PUT /api/a2p/${params.id} error:`, error);
    return NextResponse.json(
      { error: 'Failed to update registration' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  _request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const registration = getA2PRegistration(params.id);
    if (!registration) {
      return NextResponse.json(
        { error: 'Registration not found' },
        { status: 404 }
      );
    }

    deleteA2PRegistration(params.id);
    return NextResponse.json({ message: 'Registration deleted' });
  } catch (error) {
    console.error(`DELETE /api/a2p/${params.id} error:`, error);
    return NextResponse.json(
      { error: 'Failed to delete registration' },
      { status: 500 }
    );
  }
}
