import {
  BadRequestException,
  Injectable,
  Logger,
  ServiceUnavailableException,
} from '@nestjs/common';
import axios from 'axios';
import { randomInt } from 'crypto';
import { BusinessService } from './business.service';

export interface EmbeddedSignupConfig {
  enabled: boolean;
  appId: string | null;
  configId: string | null;
  graphVersion: string;
}

export interface CompleteEmbeddedSignupInput {
  code: string;
  wabaId: string;
  phoneNumberId: string;
  metaBusinessId?: string;
  /** True when the shop connected a number that stays on the WhatsApp Business app (coexistence). */
  coexistence?: boolean;
}

/**
 * Meta Tech Provider "Embedded Signup": shop owners connect WhatsApp from the
 * dashboard with a Facebook popup instead of creating their own Meta app and
 * System User token. The result is saved as a normal `whatsapp` integration so
 * message routing (by phone_number_id), sending and Flows keep working unchanged.
 */
@Injectable()
export class WhatsAppEmbeddedSignupService {
  private readonly logger = new Logger(WhatsAppEmbeddedSignupService.name);

  constructor(private readonly businessService: BusinessService) {}

  private get appId() {
    return process.env.META_APP_ID?.trim() || '';
  }

  private get appSecret() {
    return (
      process.env.META_APP_SECRET?.trim() ||
      process.env.WHATSAPP_APP_SECRET?.trim() ||
      ''
    );
  }

  private get configId() {
    return process.env.META_EMBEDDED_SIGNUP_CONFIG_ID?.trim() || '';
  }

  get graphVersion() {
    return process.env.META_GRAPH_VERSION?.trim() || 'v24.0';
  }

  private graphUrl(path: string) {
    return `https://graph.facebook.com/${this.graphVersion}/${path}`;
  }

  getPublicConfig(): EmbeddedSignupConfig {
    const enabled = !!(this.appId && this.appSecret && this.configId);
    return {
      enabled,
      appId: this.appId || null,
      configId: this.configId || null,
      graphVersion: this.graphVersion,
    };
  }

  async complete(businessId: string, input: CompleteEmbeddedSignupInput) {
    if (!this.getPublicConfig().enabled) {
      throw new ServiceUnavailableException(
        'WhatsApp quick connect is not configured on the server yet (META_APP_ID, META_APP_SECRET/WHATSAPP_APP_SECRET, META_EMBEDDED_SIGNUP_CONFIG_ID).',
      );
    }

    const code = input.code?.trim();
    const wabaId = input.wabaId?.trim();
    const phoneNumberId = input.phoneNumberId?.trim();
    const idPattern = /^\d{5,25}$/;
    if (!code) throw new BadRequestException('Missing authorization code');
    if (!wabaId || !idPattern.test(wabaId)) {
      throw new BadRequestException('Missing or invalid WhatsApp Business Account ID');
    }
    if (!phoneNumberId || !idPattern.test(phoneNumberId)) {
      throw new BadRequestException('Missing or invalid Phone Number ID');
    }

    // 1. Exchange the one-time code for a business integration token.
    //    The JS SDK popup flow is exchanged WITHOUT a redirect_uri.
    const accessToken = await this.exchangeCode(code);

    // 2. Confirm the token can see this number and that it belongs to this WABA
    //    (never trust IDs sent from the browser on their own).
    const phone = await this.verifyPhoneInWaba(accessToken, wabaId, phoneNumberId);

    // 3. Save as the shop's WhatsApp integration, keeping any Flow/catalog
    //    settings they already configured. This also enforces "one number per shop".
    const existing = ((await this.businessService.getDecryptedCredentials(
      businessId,
      'whatsapp',
    )) || {}) as Record<string, unknown>;
    const keepExisting =
      existing.phoneNumberId && String(existing.phoneNumberId) !== phoneNumberId
        ? this.pickNonConnectionSettings(existing)
        : existing;

    const registrationPinSecret =
      (keepExisting.registrationPinSecret as string | undefined) ||
      String(randomInt(0, 1_000_000)).padStart(6, '0');

    const credentials: Record<string, unknown> = {
      ...keepExisting,
      phoneNumberId,
      accessToken,
      wabaId,
      metaBusinessId: input.metaBusinessId?.trim() || keepExisting.metaBusinessId || null,
      connectionMethod: 'embedded_signup',
      coexistence: input.coexistence === true,
      displayPhoneNumber: phone.display_phone_number || null,
      verifiedName: phone.verified_name || null,
      registrationPinSecret,
      embeddedSignupAt: new Date().toISOString(),
    };

    const integration = await this.businessService.connectIntegration(businessId, {
      integrationType: 'whatsapp',
      integrationName: 'Meta WhatsApp Cloud API',
      credentials,
    });

    // 4. Subscribe our app to the shop's WABA so their messages reach our webhook.
    const warnings: string[] = [];
    try {
      await axios.post(
        this.graphUrl(`${wabaId}/subscribed_apps`),
        {},
        { headers: { Authorization: `Bearer ${accessToken}` } },
      );
    } catch (err) {
      warnings.push(`Webhook subscription failed: ${this.graphError(err)}`);
    }

    // 5. Register the number for Cloud API. Coexistence numbers stay on the
    //    WhatsApp Business app and must NOT be registered.
    if (!input.coexistence) {
      try {
        await axios.post(
          this.graphUrl(`${phoneNumberId}/register`),
          { messaging_product: 'whatsapp', pin: registrationPinSecret },
          { headers: { Authorization: `Bearer ${accessToken}` } },
        );
      } catch (err) {
        warnings.push(`Phone number registration failed: ${this.graphError(err)}`);
      }
    }

    warnings.forEach((w) => this.logger.warn(`[business ${businessId}] ${w}`));

    return {
      success: true,
      integrationId: integration.id,
      displayPhoneNumber: phone.display_phone_number || null,
      verifiedName: phone.verified_name || null,
      warnings,
      message:
        warnings.length === 0
          ? `WhatsApp connected: ${phone.verified_name || ''} ${phone.display_phone_number || ''}`.trim()
          : 'WhatsApp connected, but some setup steps need attention.',
    };
  }

  private async exchangeCode(code: string): Promise<string> {
    try {
      const res = await axios.get(this.graphUrl('oauth/access_token'), {
        params: {
          client_id: this.appId,
          client_secret: this.appSecret,
          code,
        },
      });
      const token = res.data?.access_token;
      if (!token) throw new Error('Meta did not return an access token');
      return token;
    } catch (err) {
      throw new BadRequestException(
        `Could not complete Meta sign-in: ${this.graphError(err)}`,
      );
    }
  }

  private async verifyPhoneInWaba(
    accessToken: string,
    wabaId: string,
    phoneNumberId: string,
  ): Promise<{ id: string; display_phone_number?: string; verified_name?: string }> {
    try {
      const res = await axios.get(this.graphUrl(`${wabaId}/phone_numbers`), {
        params: { fields: 'id,display_phone_number,verified_name', limit: 100 },
        headers: { Authorization: `Bearer ${accessToken}` },
      });
      const phones: any[] = res.data?.data || [];
      const match = phones.find((p) => String(p.id) === phoneNumberId);
      if (!match) {
        throw new Error('The selected phone number does not belong to this WhatsApp Business Account');
      }
      return match;
    } catch (err) {
      throw new BadRequestException(
        `Could not verify WhatsApp number: ${this.graphError(err)}`,
      );
    }
  }

  /** When switching to a different number, keep shop settings but drop old connection data. */
  private pickNonConnectionSettings(creds: Record<string, unknown>) {
    const connectionKeys = new Set([
      'phoneNumberId',
      'accessToken',
      'wabaId',
      'metaBusinessId',
      'connectionMethod',
      'coexistence',
      'displayPhoneNumber',
      'verifiedName',
      'registrationPinSecret',
      'embeddedSignupAt',
    ]);
    return Object.fromEntries(
      Object.entries(creds).filter(([k]) => !connectionKeys.has(k)),
    );
  }

  private graphError(err: unknown): string {
    const anyErr = err as any;
    return (
      anyErr?.response?.data?.error?.error_user_msg ||
      anyErr?.response?.data?.error?.message ||
      anyErr?.message ||
      String(err)
    );
  }
}
