/**
 * Webhook Registration API
 * POST /api/webhooks/register — Register all webhooks with Autotask
 * POST /api/webhooks/register?entity=Tickets — Register a single entity
 */

import { NextRequest, NextResponse } from 'next/server';
import { AutotaskWebhookManager } from '@/lib/services/autotask-webhook-manager';
import { WebhookEntityType, WEBHOOK_SUPPORTED_ENTITIES } from '@/lib/types/webhook';

export async function POST(request: NextRequest) {
  try {
    const manager = new AutotaskWebhookManager();
    const { searchParams } = new URL(request.url);
    const entityParam = searchParams.get('entity');

    if (entityParam) {
      // Register a single entity type
      const entityType = entityParam as WebhookEntityType;
      if (!WEBHOOK_SUPPORTED_ENTITIES.includes(entityType)) {
        return NextResponse.json(
          { error: `Unsupported entity type: ${entityParam}. Supported: ${WEBHOOK_SUPPORTED_ENTITIES.join(', ')}` },
          { status: 400 }
        );
      }

      const result = await manager.registerWebhook(entityType);
      return NextResponse.json({ success: true, results: [result] });
    }

    // Register all supported entities
    const results = await manager.registerAll();
    const allSuccess = results.every(r => r.success);

    return NextResponse.json({
      success: allSuccess,
      results,
      summary: {
        total: results.length,
        succeeded: results.filter(r => r.success).length,
        failed: results.filter(r => !r.success).length,
      },
    });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    console.error('[WEBHOOK-REGISTER] Error:', msg);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}

/**
 * DELETE /api/webhooks/register — Deregister all webhooks
 * DELETE /api/webhooks/register?entity=Tickets — Deregister a single entity
 */
export async function DELETE(request: NextRequest) {
  try {
    const manager = new AutotaskWebhookManager();
    const { searchParams } = new URL(request.url);
    const entityParam = searchParams.get('entity');

    if (entityParam) {
      const entityType = entityParam as WebhookEntityType;
      if (!WEBHOOK_SUPPORTED_ENTITIES.includes(entityType)) {
        return NextResponse.json(
          { error: `Unsupported entity type: ${entityParam}` },
          { status: 400 }
        );
      }

      // Find the webhook ID from DB
      const { postgresClient } = await import('@/lib/services/postgres-client');
      const result = await postgresClient.query<{ autotask_webhook_id: string }>(
        `SELECT autotask_webhook_id FROM webhook_configs WHERE entity_type = $1 AND autotask_webhook_id IS NOT NULL`,
        [entityType]
      );

      if (result.rows.length === 0 || !result.rows[0].autotask_webhook_id) {
        return NextResponse.json({ error: `No webhook registered for ${entityType}` }, { status: 404 });
      }

      await manager.deleteWebhook(entityType, parseInt(result.rows[0].autotask_webhook_id));
      return NextResponse.json({ success: true, entityType });
    }

    // Deregister all
    await manager.deregisterAll();
    return NextResponse.json({ success: true, message: 'All webhooks deregistered' });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    console.error('[WEBHOOK-DEREGISTER] Error:', msg);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
