import { Injectable } from '@nestjs/common';
import { createHash, randomBytes } from 'crypto';
import { PrismaService } from '../../../prisma/prisma.service';
import { EncryptionService } from '../../../common/services/encryption.service';
import { normalizePhoneNumber } from '../../../common/utils/phone.util';
import { ShoppingFlowService } from './shopping-flow.service';

const hash = (token: string) =>
  createHash('sha256').update(token).digest('hex');

@Injectable()
export class PaymentContactFlowService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly encryption: EncryptionService,
    private readonly shopping: ShoppingFlowService,
  ) {}

  private async config(businessId: string) {
    const integration = await this.prisma.businessIntegration.findFirst({
      where: {
        businessId,
        integrationType: 'whatsapp',
        status: 'ACTIVE',
        business: { status: 'ACTIVE' },
      },
    });
    if (!integration) return null;
    const cfg = this.encryption.decryptJson<any>(
      integration.credentialsEncrypted,
    );
    return cfg.paymentContactFlowEnabled === true &&
      typeof cfg.paymentContactFlowId === 'string' &&
      cfg.paymentContactFlowId.trim()
      ? cfg
      : null;
  }

  async launch(
    businessId: string,
    customerId: string,
    phone: string,
    orderId: string,
  ) {
    const cfg = await this.config(businessId);
    if (
      !cfg ||
      !process.env.WHATSAPP_APP_SECRET ||
      !process.env.WHATSAPP_FLOWS_PRIVATE_KEY_PATH
    )
      return null;
    const customer = await this.prisma.customer.findFirst({
      where: { id: customerId, businessId, whatsappNumber: phone },
    });
    if (
      !customer ||
      !(await this.shopping.cardCheckout(businessId, phone, orderId))
    )
      return null;
    const token = randomBytes(32).toString('hex');
    await this.prisma.paymentContactFlowSession.create({
      data: {
        id: hash(token),
        businessId,
        customerId,
        orderId,
        phone,
        expiresAt: new Date(Date.now() + 30 * 60_000),
      },
    });
    return {
      text: 'Confirm your payment contact number before opening secure Visa/Mastercard checkout.',
      payload: {
        type: 'interactive' as const,
        interactive: {
          type: 'flow',
          body: {
            text: 'Confirm your contact phone number. You will enter card details only on the payment provider’s secure checkout page.',
          },
          action: {
            name: 'flow',
            parameters: {
              flow_message_version: '3',
              flow_id: cfg.paymentContactFlowId,
              flow_token: token,
              flow_cta: 'Pay by card',
              flow_action: 'data_exchange',
            },
          },
        },
      },
    };
  }

  private async contact(
    session: {
      businessId: string;
      customerId: string;
      orderId: string;
      phone: string;
    },
    message = '',
  ) {
    const order = await this.prisma.order.findFirst({
      where: {
        id: session.orderId,
        businessId: session.businessId,
        customerId: session.customerId,
        customerPhone: session.phone,
        status: 'PENDING',
        paymentStatus: 'UNPAID',
      },
      select: { orderNumber: true, totalAmount: true, currency: true },
    });
    if (!order) throw new Error('FLOW_EXPIRED');
    const summary = `Order ${order.orderNumber}\nTotal: ${order.currency} ${order.totalAmount.toFixed(2)}`;
    return {
      screen: 'PAYMENT_CONTACT',
      data: {
        phone: session.phone,
        message: message ? `${summary}\n\n${message}` : summary,
      },
    };
  }
  private ready(token: string) {
    return {
      screen: 'PAYMENT_READY',
      data: {
        message:
          'Your contact number has been saved. Return to chat to open secure Visa/Mastercard checkout.',
        completion_value: `card_flow:${token}`,
      },
    };
  }

  async exchange(request: any): Promise<any> {
    if (request.action === 'ping') return { data: { status: 'active' } };
    const token = request.flow_token;
    if (typeof token !== 'string' || !/^[a-f0-9]{64}$/.test(token))
      throw new Error('FLOW_EXPIRED');
    const session = await this.prisma.paymentContactFlowSession.findUnique({
      where: { id: hash(token) },
    });
    if (
      !session ||
      session.expiresAt <= new Date() ||
      !(await this.config(session.businessId)) ||
      !(await this.shopping.cardCheckout(
        session.businessId,
        session.phone,
        session.orderId,
      ))
    )
      throw new Error('FLOW_EXPIRED');
    if (request.data?.error) return { data: { acknowledged: true } };
    if (session.contactPhone) return this.ready(token);
    if (request.action === 'INIT' || request.action === 'BACK')
      return this.contact(session);
    if (
      request.action !== 'data_exchange' ||
      request.screen !== 'PAYMENT_CONTACT'
    )
      return this.contact(session);
    const raw = request.data?.phone;
    if (
      typeof raw !== 'string' ||
      raw.length > 32 ||
      !/^\+?[\d ()-]+$/.test(raw)
    )
      return this.contact(
        session,
        'Enter a valid phone number with country code.',
      );
    const phone = normalizePhoneNumber(raw);
    if (!/^[1-9]\d{7,14}$/.test(phone))
      return this.contact(
        session,
        'Use a country code, for example +263771234567.',
      );
    for (let attempt = 0; attempt < 3; attempt++) {
      try {
        await this.prisma.$transaction(
          async (tx) => {
            const current =
              await tx.paymentContactFlowSession.findUniqueOrThrow({
                where: { id: session.id },
              });
            if (current.expiresAt <= new Date())
              throw new Error('FLOW_EXPIRED');
            if (current.contactPhone) return;
            const order = await tx.order.updateMany({
              where: {
                id: session.orderId,
                businessId: session.businessId,
                customerId: session.customerId,
                customerPhone: session.phone,
                paymentStatus: 'UNPAID',
                status: 'PENDING',
              },
              data: { paymentContactPhone: phone },
            });
            if (order.count !== 1) throw new Error('FLOW_EXPIRED');
            await tx.paymentContactFlowSession.update({
              where: { id: session.id },
              data: { contactPhone: phone },
            });
          },
          { isolationLevel: 'Serializable' },
        );
        return this.ready(token);
      } catch (error) {
        if (error?.code !== 'P2034' || attempt === 2) throw error;
      }
    }
  }

  async checkoutFromCompletion(
    businessId: string,
    customerId: string,
    phone: string,
    token: string,
  ): Promise<string | null> {
    if (!/^[a-f0-9]{64}$/.test(token)) return null;
    const session = await this.prisma.paymentContactFlowSession.findUnique({
      where: { id: hash(token) },
    });
    if (
      !session ||
      session.businessId !== businessId ||
      session.customerId !== customerId ||
      session.phone !== phone ||
      !session.contactPhone ||
      session.expiresAt <= new Date() ||
      !(await this.config(businessId))
    )
      return null;
    return this.shopping.cardCheckout(businessId, phone, session.orderId);
  }
}
