import { Request, Response } from 'express';
import { DMSWebhookService } from '../services/dmsWebhook.service';
import { ResponseHandler } from '../utils/responseHandler';
import logger from '../utils/logger';

/**
 * DMS Webhook Controller
 * Handles webhook callbacks from DMS system for invoice and credit note generation
 */
export class DMSWebhookController {
  private webhookService = new DMSWebhookService();

  /**
   * Handle invoice generation webhook from DMS
   * POST /api/v1/webhooks/dms/invoice
   */
  async handleInvoiceWebhook(req: Request, res: Response): Promise<void> {
    try {
      const payload = req.body;

      logger.info('[DMSWebhook] Invoice webhook received', {
        requestNumber: payload.request_number,
        documentNo: payload.document_no,
      });

      // Validate webhook signature if configured
      const isValid = await this.webhookService.validateWebhookSignature(req);
      if (!isValid) {
        logger.warn('[DMSWebhook] Invalid webhook signature');
        return ResponseHandler.error(res, 'Invalid webhook signature', 401);
      }

      // Process invoice webhook
      const result = await this.webhookService.processInvoiceWebhook(payload);

      if (!result.success) {
        logger.error('[DMSWebhook] Invoice webhook processing failed', {
          error: result.error,
          requestNumber: payload.request_number,
        });
        return ResponseHandler.error(res, result.error || 'Failed to process invoice webhook', 400);
      }

      logger.info('[DMSWebhook] Invoice webhook processed successfully', {
        requestNumber: payload.request_number,
        invoiceNumber: result.invoiceNumber,
      });

      return ResponseHandler.success(
        res,
        {
          message: 'Invoice webhook processed successfully',
          invoiceNumber: result.invoiceNumber,
          requestNumber: payload.request_number,
        },
        'Webhook processed'
      );
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      logger.error('[DMSWebhook] Error processing invoice webhook:', error);
      return ResponseHandler.error(res, 'Failed to process invoice webhook', 500, errorMessage);
    }
  }

  /**
   * Handle credit note generation webhook from DMS
   * POST /api/v1/webhooks/dms/credit-note
   */
  async handleCreditNoteWebhook(req: Request, res: Response): Promise<void> {
    try {
      const payload = req.body;

      logger.info('[DMSWebhook] Credit note webhook received', {
        requestNumber: payload.request_number,
        documentNo: payload.document_no,
      });

      // Validate webhook signature if configured
      const isValid = await this.webhookService.validateWebhookSignature(req);
      if (!isValid) {
        logger.warn('[DMSWebhook] Invalid webhook signature');
        return ResponseHandler.error(res, 'Invalid webhook signature', 401);
      }

      // Process credit note webhook
      const result = await this.webhookService.processCreditNoteWebhook(payload);

      if (!result.success) {
        logger.error('[DMSWebhook] Credit note webhook processing failed', {
          error: result.error,
          requestNumber: payload.request_number,
        });
        return ResponseHandler.error(res, result.error || 'Failed to process credit note webhook', 400);
      }

      logger.info('[DMSWebhook] Credit note webhook processed successfully', {
        requestNumber: payload.request_number,
        creditNoteNumber: result.creditNoteNumber,
      });

      return ResponseHandler.success(
        res,
        {
          message: 'Credit note webhook processed successfully',
          creditNoteNumber: result.creditNoteNumber,
          requestNumber: payload.request_number,
        },
        'Webhook processed'
      );
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      logger.error('[DMSWebhook] Error processing credit note webhook:', error);
      return ResponseHandler.error(res, 'Failed to process credit note webhook', 500, errorMessage);
    }
  }
}

