import {
  Controller,
  Get,
  Post,
  Body,
  UseGuards,
  Request,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { BusinessService } from './business.service';
import { ConnectIntegrationDto } from './dto/connect-integration.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { SubscriptionGuard } from '../subscription/subscription.guard';
import { ConnectorFactory } from '../connectors/connector.factory';
import { PaynowGateway } from '../payments/gateways/paynow.gateway';
import { PesePayGateway } from '../payments/gateways/pesepay.gateway';
import axios from 'axios';
import * as fs from 'fs';
import { AuthenticatedRequest } from '../../common/interfaces/auth-request.interface';

@Controller('api/integrations')
@UseGuards(JwtAuthGuard, SubscriptionGuard)
export class BusinessController {
  constructor(
    private readonly businessService: BusinessService,
    private readonly connectorFactory: ConnectorFactory,
  ) {}

  @Get()
  async getIntegrations(@Request() req: any) {
    const authReq = req as AuthenticatedRequest;
    return this.businessService.listIntegrations(authReq.user.id);
  }

  @Post('connect')
  async connectIntegration(
    @Request() req: any,
    @Body() dto: ConnectIntegrationDto,
  ) {
    const authReq = req as AuthenticatedRequest;
    return this.businessService.connectIntegration(authReq.user.id, dto);
  }

  @Post('test')
  @HttpCode(HttpStatus.OK)
  async testIntegration(
    @Request() req: any,
    @Body()
    body: { integrationType: string; credentials?: Record<string, any> },
  ) {
    const authReq = req as AuthenticatedRequest;
    // If credentials are provided in body (testing before save), use them; otherwise fetch saved ones
    let creds: Record<string, any> | null | undefined = body.credentials;
    const savedCreds = await this.businessService.getDecryptedCredentials(
      authReq.user.id,
      body.integrationType,
    );

    if (creds) {
      // If any credential field is masked (contains ... or ***), replace it with the saved decrypted credential
      if (savedCreds) {
        for (const [key, value] of Object.entries(creds)) {
          if (
            typeof value === 'string' &&
            (value.includes('...') || value.includes('***'))
          ) {
            creds[key] = savedCreds[key];
          }
        }
      }
    } else {
      creds = savedCreds;
    }

    if (!creds) {
      return { success: false, message: 'No credentials configured' };
    }

    // Trim string credentials
    for (const [key, value] of Object.entries(creds)) {
      if (typeof value === 'string') {
        creds[key] = value.trim();
      }
    }

    // Handle WooCommerce
    if (body.integrationType === 'woocommerce') {
      if (
        creds.isSandbox ||
        creds.consumerKey === 'ck_sandbox' ||
        creds.storeUrl?.includes('sandbox')
      ) {
        return {
          success: true,
          message: 'Sandbox WooCommerce connection successful',
        };
      }
      try {
        console.log('[WooCommerce Debug] storeUrl:', creds.storeUrl);
        console.log('[WooCommerce Debug] consumerKey:', creds.consumerKey);
        console.log(
          '[WooCommerce Debug] consumerSecret present:',
          !!creds.consumerSecret,
          '| length:',
          creds.consumerSecret?.length ?? 0,
        );
        console.log(
          '[WooCommerce Debug] consumerSecret prefix:',
          creds.consumerSecret?.substring(0, 10) ?? 'EMPTY',
        );

        // Log to file to capture keys
        try {
          fs.writeFileSync(
            'last_test_keys.json',
            JSON.stringify(creds, null, 2),
          );
        } catch (fsErr) {
          const fsErrMsg =
            fsErr instanceof Error ? fsErr.message : String(fsErr);
          console.error('Failed to write last_test_keys.json:', fsErrMsg);
        }

        const connector = this.connectorFactory.getConnector(
          'woocommerce',
          creds,
        );
        const connected = await connector.testConnection();
        if (connected) {
          return {
            success: true,
            message: 'Connected to WooCommerce successfully!',
          };
        }
        return {
          success: false,
          message:
            'Could not connect to WooCommerce. Please check your URL and keys.',
        };
      } catch (err: unknown) {
        const message = err instanceof Error ? err.message : String(err);
        return {
          success: false,
          message: `WooCommerce connection failed: ${message}`,
        };
      }
    }

    // Handle Paynow
    if (body.integrationType === 'paynow') {
      const paynow = new PaynowGateway(creds);
      return paynow.testConnection();
    }

    // Handle PesePay
    if (body.integrationType === 'pesepay') {
      const pesepay = new PesePayGateway(creds);
      return pesepay.testConnection();
    }

    // Handle WhatsApp
    if (body.integrationType === 'whatsapp') {
      if (!creds.phoneNumberId || !creds.accessToken) {
        return {
          success: false,
          message: 'Phone Number ID and Graph Access Token are required',
        };
      }
      try {
        const url = `https://graph.facebook.com/v19.0/${creds.phoneNumberId}`;
        const response = await axios.get(url, {
          headers: {
            Authorization: `Bearer ${creds.accessToken}`,
          },
        });
        if (response.data && response.data.id === creds.phoneNumberId) {
          const displayName =
            response.data.display_phone_number ||
            response.data.verified_name ||
            'WhatsApp Business Number';
          return {
            success: true,
            message: `Connected successfully! Display Name: ${displayName}`,
          };
        }
        return {
          success: false,
          message: 'Invalid response from Meta API',
        };
      } catch (err: any) {
        const errorMsg = err.response?.data?.error?.message || err.message;
        return {
          success: false,
          message: `Meta API connection failed: ${errorMsg}`,
        };
      }
    }

    // Handle Meta / WhatsApp Native Catalog
    if (
      body.integrationType === 'meta_catalog' ||
      body.integrationType === 'whatsapp_catalog' ||
      body.integrationType === 'meta'
    ) {
      if (!creds.catalogId || !creds.accessToken) {
        return {
          success: false,
          message: 'Meta Catalog ID and Access Token are required',
        };
      }
      try {
        const connector = this.connectorFactory.getConnector(
          'meta_catalog',
          creds,
        );
        const connected = await connector.testConnection();
        if (connected) {
          return {
            success: true,
            message: `Connected to Meta Catalog (${creds.catalogId}) successfully!`,
          };
        }
        return {
          success: false,
          message:
            'Could not verify Meta Catalog. Please check your Catalog ID and System User Token.',
        };
      } catch (err: unknown) {
        const message = err instanceof Error ? err.message : String(err);
        return { success: false, message: `${message}` };
      }
    }

    return {
      success: false,
      message: `Unsupported integration type: ${body.integrationType}`,
    };
  }

  @Post('woocommerce/setup-webhooks')
  @HttpCode(HttpStatus.OK)
  async setupWooCommerceWebhooks(
    @Request() req: any,
    @Body() body: { publicUrl?: string },
  ) {
    const authReq = req as AuthenticatedRequest;
    const businessId = authReq.user.id;
    let baseUrl = '';

    if (body && body.publicUrl) {
      baseUrl = body.publicUrl.replace(/\/$/, '');
    } else {
      const protocol = (req.headers['x-forwarded-proto'] as string) || 'http';
      const host =
        (req.headers['x-forwarded-host'] as string) || req.headers.host;
      baseUrl = `${protocol}://${host}`;
    }

    const credentials = await this.businessService.getDecryptedCredentials(
      businessId,
      'woocommerce',
    );
    if (!credentials) {
      return {
        success: false,
        message:
          'WooCommerce credentials not found or integration is inactive.',
      };
    }

    if (credentials.isSandbox) {
      return {
        success: true,
        message: 'Running in Sandbox mode. Webhooks are mock-simulated.',
      };
    }

    try {
      const connector = this.connectorFactory.getConnector(
        'woocommerce',
        credentials,
      );
      const deliveryUrl = `${baseUrl}/webhooks/woocommerce/orders?businessId=${businessId}`;
      const success = await connector.registerWebhooks(deliveryUrl);
      if (success) {
        return {
          success: true,
          message: `Successfully registered webhooks for ${deliveryUrl}`,
        };
      }
      return {
        success: false,
        message: 'Failed to register WooCommerce webhooks.',
      };
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : String(err);
      return {
        success: false,
        message: `Error registering webhooks: ${message}`,
      };
    }
  }
}
