import { Injectable, Logger } from '@nestjs/common';
import { createHash, randomBytes } from 'crypto';
import axios from 'axios';
import sharp from 'sharp';
import { PrismaService } from '../../../prisma/prisma.service';
import { EncryptionService } from '../../../common/services/encryption.service';
import { ProductsService } from '../../commerce/services/products.service';
import {
  filterAllForChatbot,
  filterForChatbot,
} from '../../../common/utils/chatbot-catalog';

interface FlowConfig {
  shoppingFlowEnabled?: boolean;
  shoppingFlowId?: string;
  searchFlowId?: string;
  searchFlowVisual?: boolean;
  shoppingTermsVersion?: string;
  shoppingTermsUrl?: string;
  shoppingPrivacyUrl?: string;
  shoppingTermsSummary?: string;
  shoppingTermsText?: string;
  shoppingPrivacyText?: string;
}
const hash = (token: string) =>
  createHash('sha256').update(token).digest('hex');
const categoriesOf = (description: string | null) =>
  (description || '')
    .match(/^Categories:\s*(.+)$/im)?.[1]
    .split(',')
    .map((s) => s.trim())
    .filter(Boolean) || [];
// A missing image must not prevent shopping. Flow Image takes base64 image bytes.
const PLACEHOLDER =
  'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=';

@Injectable()
export class ShoppingFlowService {
  private readonly logger = new Logger(ShoppingFlowService.name);
  constructor(
    private readonly prisma: PrismaService,
    private readonly encryption: EncryptionService,
    private readonly products: ProductsService,
  ) {}

  private async config(businessId: string): Promise<FlowConfig | null> {
    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<FlowConfig>(
      integration.credentialsEncrypted,
    );
    const origin = (
      process.env.PUBLIC_URL ||
      process.env.BACKEND_URL ||
      ''
    ).replace(/\/$/, '');
    if (cfg.shoppingTermsVersion && origin.startsWith('https://')) {
      const base = `${origin}/whatsapp/policies/${encodeURIComponent(businessId)}/${encodeURIComponent(cfg.shoppingTermsVersion)}`;
      if (!cfg.shoppingTermsUrl && cfg.shoppingTermsText?.trim())
        cfg.shoppingTermsUrl = `${base}/terms`;
      if (!cfg.shoppingPrivacyUrl && cfg.shoppingPrivacyText?.trim())
        cfg.shoppingPrivacyUrl = `${base}/privacy`;
    }
    if (!cfg.shoppingTermsSummary && cfg.shoppingTermsText?.trim())
      cfg.shoppingTermsSummary = cfg.shoppingTermsText.slice(0, 3400);
    if (
      cfg.shoppingFlowEnabled !== true ||
      !cfg.shoppingFlowId ||
      !cfg.shoppingTermsVersion ||
      !cfg.shoppingTermsSummary ||
      !cfg.shoppingTermsUrl?.startsWith('https://') ||
      !cfg.shoppingPrivacyUrl?.startsWith('https://')
    )
      return null;
    if (
      cfg.shoppingTermsSummary.length > 3500 ||
      cfg.shoppingTermsVersion.length > 100
    )
      return null;
    return cfg;
  }

  async launch(
    businessId: string,
    customerId: string,
    phone: string,
    mode: 'basket' | 'consent' | 'search' = 'basket',
  ) {
    const cfg = await this.config(businessId);
    if (
      !cfg ||
      (mode === 'search' && !cfg.searchFlowId) ||
      !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) return null;
    const entryData =
      mode === 'search' && !cfg.searchFlowVisual
        ? (await this.searchScreen(businessId)).data
        : undefined;
    const token = randomBytes(32).toString('hex');
    await this.prisma.shoppingFlowSession.create({
      data: {
        id: hash(token),
        businessId,
        customerId,
        phone,
        termsVersion: cfg.shoppingTermsVersion!,
        selectionJson: JSON.stringify({
          mode,
          visualSearch: mode === 'search' && cfg.searchFlowVisual === true,
        }),
        expiresAt: new Date(Date.now() + 30 * 60_000),
      },
    });
    return {
      text:
        mode === 'consent'
          ? 'Please read and accept our Shopping Terms and Privacy Notice before continuing.'
          : 'Search products and return to the shopping chat.',
      payload: {
        type: 'interactive' as const,
        interactive: {
          type: 'flow',
          body: {
            text:
              mode === 'consent'
                ? 'Before you start shopping, please read and accept our Shopping Terms and Privacy Notice.'
                : 'Search our products and choose one to continue in chat.',
          },
          action: {
            name: 'flow',
            parameters: {
              flow_message_version: '3',
              flow_id:
                mode === 'search'
                  ? cfg.searchFlowId || cfg.shoppingFlowId
                  : cfg.shoppingFlowId,
              flow_token: token,
              flow_cta:
                mode === 'consent' ? 'Review and accept' : 'Search products',
              flow_action:
                mode === 'search' && !cfg.searchFlowVisual
                  ? 'navigate'
                  : 'data_exchange',
              ...(entryData
                ? { flow_action_payload: { screen: 'SEARCH', data: entryData } }
                : {}),
            },
          },
        },
      },
    };
  }

  async needsConsent(businessId: string, customerId: string): Promise<boolean> {
    const cfg = await this.config(businessId);
    if (!cfg) return false;
    return !(await this.accepted({
      businessId,
      customerId,
      termsVersion: cfg.shoppingTermsVersion!,
    }));
  }

  private finish(token: string, kind: 'consent' | 'search') {
    return {
      screen: 'SUCCESS',
      data: {
        extension_message_response: {
          params: { flow_token: token, value: `${kind}_flow:${token}` },
        },
      },
    };
  }

  async completion(
    businessId: string,
    customerId: string,
    phone: string,
    token: string,
    kind: 'consent' | 'search',
  ) {
    if (!/^[a-f0-9]{64}$/.test(token)) return null;
    const session = await this.prisma.shoppingFlowSession.findUnique({
      where: { id: hash(token) },
    });
    if (
      !session ||
      session.businessId !== businessId ||
      session.customerId !== customerId ||
      session.phone !== phone ||
      session.expiresAt <= new Date() ||
      !session.resultJson
    )
      return null;
    const cfg = await this.config(businessId);
    if (
      !cfg ||
      cfg.shoppingTermsVersion !== session.termsVersion ||
      !(await this.accepted(session))
    )
      return null;
    const result = JSON.parse(session.resultJson);
    if (result.kind !== kind) return null;
    if (kind === 'consent') return { kind };
    const item = await this.item(businessId, result.selected);
    return item
      ? { kind, productId: item.productId, variantId: item.variantId }
      : null;
  }

  async hostedWalletCheckout(
    businessId: string,
    phone: string,
    orderId: string,
  ): Promise<string | null> {
    const payment = await this.prisma.payment.findFirst({
      where: {
        businessId,
        orderId,
        gateway: 'pesepay',
        currency: 'USD',
        status: 'PENDING',
        order: {
          customerPhone: phone,
          paymentStatus: 'UNPAID',
          status: 'PENDING',
        },
      },
      orderBy: { createdAt: 'desc' },
    });
    if (!payment?.paymentLink) return null;
    try {
      const url = new URL(payment.paymentLink);
      return url.protocol === 'https:' && !url.username && !url.password
        ? url.href
        : null;
    } catch {
      return null;
    }
  }

  async cardCheckout(
    businessId: string,
    phone: string,
    orderId: string,
  ): Promise<string | null> {
    const payment = await this.prisma.payment.findFirst({
      where: {
        businessId,
        orderId,
        status: 'PENDING',
        gateway: { in: ['paynow', 'pesepay'] },
        order: { customerPhone: phone, paymentStatus: 'UNPAID' },
      },
      orderBy: { createdAt: 'desc' },
    });
    if (!payment?.paymentLink) return null;
    const integration = await this.prisma.businessIntegration.findFirst({
      where: { businessId, integrationType: payment.gateway, status: 'ACTIVE' },
    });
    if (!integration) return null;
    const credentials = this.encryption.decryptJson<any>(
      integration.credentialsEncrypted,
    );
    if (
      credentials.cardPaymentsEnabled !== true ||
      credentials.isSandbox === true
    )
      return null;
    try {
      const url = new URL(payment.paymentLink);
      if (url.protocol !== 'https:' || url.username || url.password)
        return null;
      return url.href;
    } catch {
      return null;
    }
  }

  private async accepted(session: {
    businessId: string;
    customerId: string;
    termsVersion: string;
  }) {
    return this.prisma.shoppingTermsAcceptance.findUnique({
      where: {
        businessId_customerId_version: {
          businessId: session.businessId,
          customerId: session.customerId,
          version: session.termsVersion,
        },
      },
    });
  }

  private terms(cfg: FlowConfig, message = '') {
    return {
      screen: 'TERMS',
      data: {
        summary: cfg.shoppingTermsSummary,
        terms_url: cfg.shoppingTermsUrl,
        privacy_url: cfg.shoppingPrivacyUrl,
        message,
      },
    };
  }

  private async productOptions(
    products: any[],
    limit: number,
    thumbnails: boolean,
  ) {
    const options = products
      .flatMap((p) => {
        const variants = p.variants?.length ? p.variants : [null];
        return variants.map((v) => {
          const source = v || p;
          const stock = v?.stockQuantity ?? p.stockQuantity;
          return {
            id: v ? `${p.id}:${v.id}` : p.id,
            title:
              `${p.name}${v ? ` - ${v.name || v.sku || 'Option'}` : ''}`.slice(
                0,
                30,
              ),
            description: `${p.currency} ${source.price.toFixed(2)} · ${source.stockStatus === 'outofstock' || stock === 0 ? 'Out of stock' : 'In stock'}`,
            enabled: source.stockStatus !== 'outofstock' && stock !== 0,
            imageUrl: p.imageUrl,
          };
        });
      })
      .slice(0, limit);
    const pending = new Map<string, Promise<string>>();
    return Promise.all(
      options.map(async ({ imageUrl, ...option }) => {
        if (!thumbnails) return option;
        let image = PLACEHOLDER;
        if (imageUrl) {
          if (!pending.has(imageUrl))
            pending.set(imageUrl, this.image(imageUrl));
          const candidate = await pending.get(imageUrl)!;
          if (Buffer.byteLength(candidate, 'base64') <= 80_000)
            image = candidate;
        }
        return { ...option, image, 'alt-text': option.title };
      }),
    );
  }

  private async searchScreen(
    businessId: string,
    message = '',
    visual = false,
    category = 'all',
  ) {
    const products = filterAllForChatbot(
      await this.products.listProducts(businessId),
    );
    const names = [
      ...new Set(products.flatMap((p) => categoriesOf(p.description))),
    ]
      .sort()
      .slice(0, visual ? 7 : 19);
    const featured = visual
      ? await this.productOptions(
          products.filter(
            (p) =>
              p.stockStatus !== 'outofstock' &&
              p.stockQuantity !== 0 &&
              (category === 'all' ||
                categoriesOf(p.description).includes(category)),
          ),
          category === 'all' ? 4 : 8,
          true,
        )
      : [];
    return {
      screen: 'SEARCH',
      data: {
        message:
          visual && !featured.length
            ? 'No available products in this category. Choose another category.'
            : message,
        ...(visual
          ? {
              featured,
              has_featured: featured.length > 0,
              selected_categories: [category],
            }
          : {}),
        categories: [
          { id: 'all', title: 'All products' },
          ...names.map((name) => ({ id: name, title: name.slice(0, 30) })),
        ],
      },
    };
  }

  async exchange(request: any): Promise<any> {
    if (request.action === 'ping') return { data: { status: 'active' } };
    if (
      typeof request.flow_token !== 'string' ||
      request.flow_token.length !== 64
    )
      throw new Error('FLOW_EXPIRED');
    const session = await this.prisma.shoppingFlowSession.findUnique({
      where: { id: hash(request.flow_token) },
    });
    if (!session || session.expiresAt <= new Date())
      throw new Error('FLOW_EXPIRED');
    const cfg = await this.config(session.businessId);
    if (!cfg || cfg.shoppingTermsVersion !== session.termsVersion)
      throw new Error('FLOW_EXPIRED');
    if (request.data?.error) {
      // Only protocol diagnostics: never log Flow tokens, customer input or decrypted payloads.
      const code = String(request.data.error)
        .replace(/[^a-zA-Z0-9_.-]/g, '')
        .slice(0, 100);
      const screen = ['TERMS', 'SEARCH', 'RESULTS', 'PRODUCT', 'DONE'].includes(
        request.screen,
      )
        ? request.screen
        : 'INIT';
      this.logger.warn(
        `WhatsApp Flow validation error: ${code}; screen=${screen}`,
      );
      return { data: { acknowledged: true } };
    }
    const state = JSON.parse(session.selectionJson);
    const mode = state.mode || 'basket';
    const visual = state.visualSearch === true;
    const searchScreen = async (message = '', category = 'all') => {
      const response = await this.searchScreen(
        session.businessId,
        message,
        visual,
        category,
      );
      if (visual)
        await this.prisma.shoppingFlowSession.update({
          where: { id: session.id },
          data: {
            selectionJson: JSON.stringify({
              ...state,
              featuredCategory: category,
              featuredOffered: (response.data.featured || [])
                .filter((p) => p.enabled)
                .map((p) => p.id),
            }),
          },
        });
      return response;
    };
    if (session.resultJson) {
      const result = JSON.parse(session.resultJson);
      return result.kind
        ? this.finish(request.flow_token, result.kind)
        : { screen: 'DONE', data: result };
    }
    const accepted = await this.accepted(session);
    if (request.action === 'INIT')
      return accepted ? searchScreen() : this.terms(cfg);
    if (request.action !== 'data_exchange')
      return accepted ? searchScreen() : this.terms(cfg);
    const data = request.data || {};
    if (request.screen === 'TERMS') {
      if (data.accepted !== true)
        return this.terms(cfg, 'Please accept the terms to continue.');
      await this.prisma.shoppingTermsAcceptance.upsert({
        where: {
          businessId_customerId_version: {
            businessId: session.businessId,
            customerId: session.customerId,
            version: session.termsVersion,
          },
        },
        create: {
          businessId: session.businessId,
          customerId: session.customerId,
          version: session.termsVersion,
          termsUrl: cfg.shoppingTermsUrl!,
        },
        update: {},
      });
      if (mode === 'consent') {
        await this.prisma.shoppingFlowSession.update({
          where: { id: session.id },
          data: { resultJson: JSON.stringify({ kind: 'consent' }) },
        });
        return this.finish(request.flow_token, 'consent');
      }
      return searchScreen();
    }
    if (!accepted) return this.terms(cfg);
    if (request.screen === 'SEARCH') {
      const query =
        typeof data.query === 'string' ? data.query.trim().slice(0, 100) : '';
      const category = Array.isArray(data.category)
        ? data.category[0] || 'all'
        : typeof data.category === 'string'
          ? data.category
          : 'all';
      if (visual && data.action === 'category_change') {
        return searchScreen(
          category === 'all' ? '' : `Products in ${category}`,
          category,
        );
      }
      if (
        visual &&
        mode === 'search' &&
        !query &&
        category === (state.featuredCategory || 'all') &&
        typeof data.featured === 'string' &&
        state.featuredOffered?.includes(data.featured)
      ) {
        const item = await this.item(session.businessId, data.featured);
        if (!item)
          return searchScreen(
            'This featured product is no longer available. Search again.',
          );
        await this.prisma.shoppingFlowSession.update({
          where: { id: session.id },
          data: {
            resultJson: JSON.stringify({
              kind: 'search',
              selected: data.featured,
            }),
          },
        });
        return this.finish(request.flow_token, 'search');
      }
      const products = filterAllForChatbot(
        await this.products.listProducts(session.businessId, query),
      ).filter(
        (p) =>
          category === 'all' || categoriesOf(p.description).includes(category),
      );
      const options = await this.productOptions(
        products,
        visual ? 8 : 20,
        visual,
      );
      if (!options.length || options.every((o) => !o.enabled))
        return searchScreen(
          'No available products found. Try another search or category.',
        );
      await this.prisma.shoppingFlowSession.update({
        where: { id: session.id },
        data: {
          selectionJson: JSON.stringify({
            mode,
            visualSearch: visual,
            offered: options.filter((o) => o.enabled).map((o) => o.id),
            resultsData: { products: options },
          }),
        },
      });
      return {
        screen: 'RESULTS',
        data: {
          products: options,
          message: `Showing up to ${visual ? 8 : 20} products. Select one to continue shopping in chat.`,
        },
      };
    }
    const selection = JSON.parse(session.selectionJson);
    if (request.screen === 'RESULTS') {
      if (
        typeof data.product !== 'string' ||
        !selection.offered?.includes(data.product)
      )
        return {
          screen: 'RESULTS',
          data: {
            ...selection.resultsData,
            message:
              'Please select an available product. Use Back to change your search.',
          },
        };
      const item = await this.item(session.businessId, data.product);
      if (!item)
        return {
          screen: 'RESULTS',
          data: {
            ...selection.resultsData,
            message:
              'This product is no longer available. Use Back to search again.',
          },
        };
      if (mode === 'search') {
        await this.prisma.shoppingFlowSession.update({
          where: { id: session.id },
          data: {
            resultJson: JSON.stringify({
              kind: 'search',
              selected: data.product,
            }),
          },
        });
        return this.finish(request.flow_token, 'search');
      }
      const productData = {
        name: item.name,
        price: `${item.currency} ${item.price.toFixed(2)}`,
        stock: 'In stock',
        image: await this.image(item.imageUrl),
        message: '',
        quantities: Array.from(
          { length: Math.min(10, item.stock ?? 10) },
          (_, i) => ({ id: String(i + 1), title: String(i + 1) }),
        ),
      };
      await this.prisma.shoppingFlowSession.update({
        where: { id: session.id },
        data: {
          selectionJson: JSON.stringify({
            ...selection,
            selected: data.product,
            productData,
          }),
        },
      });
      return { screen: 'PRODUCT', data: productData };
    }
    if (request.screen === 'PRODUCT' && selection.selected) {
      const quantity =
        typeof data.quantity === 'string' && /^([1-9]|10)$/.test(data.quantity)
          ? Number(data.quantity)
          : 0;
      if (!quantity)
        return {
          screen: 'PRODUCT',
          data: {
            ...selection.productData,
            message: 'Choose a quantity from 1 to 10.',
          },
        };
      try {
        const result = await this.add(session.id, quantity);
        return { screen: 'DONE', data: result };
      } catch (error) {
        if (error?.message === 'UNAVAILABLE')
          return {
            screen: 'PRODUCT',
            data: {
              ...selection.productData,
              message:
                'Product, price, stock or basket currency changed. Use Back to search again.',
            },
          };
        throw error;
      }
    }
    return searchScreen();
  }

  private async item(
    businessId: string,
    selected: string,
    db: any = this.prisma,
  ) {
    const [id, variantId] = selected.split(':');
    const product = filterForChatbot(
      await db.product.findFirst({
        where: { id, businessId, status: 'ACTIVE' },
        include: { variants: true },
      }),
    ) as any;
    if (!product) return null;
    const variant = variantId
      ? product.variants.find((v: any) => v.id === variantId)
      : null;
    if ((variantId && !variant) || (!variantId && product.variants.length))
      return null;
    const source = variant || product;
    const stock = variant?.stockQuantity ?? product.stockQuantity;
    if (
      source.stockStatus === 'outofstock' ||
      stock === 0 ||
      (stock !== null && stock < 0) ||
      !Number.isFinite(source.price) ||
      source.price < 0
    )
      return null;
    return {
      productId: product.id,
      variantId: variant?.id || null,
      name: `${product.name}${variant ? ` - ${variant.name || variant.sku || 'Option'}` : ''}`,
      price: source.price,
      currency: product.currency,
      stock,
      imageUrl: product.imageUrl,
    };
  }

  private async add(id: string, quantity: number) {
    // Serializable transaction makes a retried/double-clicked add idempotent and keeps totals consistent.
    for (let attempt = 0; attempt < 3; attempt++) {
      try {
        return await this.prisma.$transaction(
          async (tx) => {
            const session = await tx.shoppingFlowSession.findUniqueOrThrow({
              where: { id },
            });
            if (session.resultJson) return JSON.parse(session.resultJson);
            if (session.expiresAt <= new Date())
              throw new Error('FLOW_EXPIRED');
            const selection = JSON.parse(session.selectionJson);
            const item = await this.item(
              session.businessId,
              selection.selected,
              tx,
            );
            if (
              !item ||
              (item.stock !== null && quantity > item.stock) ||
              selection.productData?.price !==
                `${item.currency} ${item.price.toFixed(2)}`
            )
              throw new Error('UNAVAILABLE');
            let cart = await tx.cart.findFirst({
              where: {
                businessId: session.businessId,
                whatsappNumber: session.phone,
                status: 'ACTIVE',
              },
              include: { items: true },
            });
            if (!cart)
              cart = await tx.cart.create({
                data: {
                  businessId: session.businessId,
                  customerId: session.customerId,
                  whatsappNumber: session.phone,
                  currency: item.currency,
                  expiresAt: new Date(Date.now() + 86400_000),
                },
                include: { items: true },
              });
            if (cart.items.length && cart.currency !== item.currency)
              throw new Error('UNAVAILABLE');
            const existing = cart.items.find(
              (i) =>
                i.productId === item.productId &&
                i.variantId === item.variantId,
            );
            const newQuantity = quantity + (existing?.quantity || 0);
            if (item.stock !== null && newQuantity > item.stock)
              throw new Error('UNAVAILABLE');
            if (existing)
              await tx.cartItem.update({
                where: { id: existing.id },
                data: {
                  quantity: newQuantity,
                  unitPrice: item.price,
                  lineTotal: Math.round(item.price * newQuantity * 100) / 100,
                },
              });
            else
              await tx.cartItem.create({
                data: {
                  cartId: cart.id,
                  productId: item.productId,
                  variantId: item.variantId,
                  quantity,
                  unitPrice: item.price,
                  lineTotal: Math.round(item.price * quantity * 100) / 100,
                },
              });
            const items = await tx.cartItem.findMany({
              where: { cartId: cart.id },
            });
            const total =
              Math.round(items.reduce((sum, i) => sum + i.lineTotal, 0) * 100) /
              100;
            await tx.cart.update({
              where: { id: cart.id },
              data: { totalAmount: total, currency: item.currency },
            });
            const result = {
              message: `${quantity} × ${item.name} added to your basket. Basket total: ${item.currency} ${total.toFixed(2)}. Continue in chat to shop more or checkout.`,
            };
            await tx.shoppingFlowSession.update({
              where: { id },
              data: { resultJson: JSON.stringify(result) },
            });
            return result;
          },
          { isolationLevel: 'Serializable' },
        );
      } catch (error) {
        if (error?.code !== 'P2034' || attempt === 2) throw error;
      }
    }
  }

  private async image(imageUrl: string | null): Promise<string> {
    if (!imageUrl) return PLACEHOLDER;
    try {
      const url = new URL(imageUrl);
      // Operator-controlled public CDN origins only. Redirects are disabled to prevent SSRF.
      const allowed = (process.env.WHATSAPP_FLOWS_IMAGE_ORIGINS || '')
        .split(',')
        .map((s) => s.trim());
      if (
        url.protocol !== 'https:' ||
        url.username ||
        url.password ||
        !allowed.includes(url.origin)
      )
        return PLACEHOLDER;
      const response = await axios.get(imageUrl, {
        responseType: 'arraybuffer',
        timeout: 2500,
        maxRedirects: 0,
        maxContentLength: 5_000_000,
        maxBodyLength: 5_000_000,
      });
      if (
        !/^image\/(png|jpeg|webp)(;|$)/i.test(
          String(response.headers['content-type']),
        )
      )
        return PLACEHOLDER;
      const thumbnail = await sharp(Buffer.from(response.data), {
        limitInputPixels: 25_000_000,
      })
        .rotate()
        .resize(240, 240, { fit: 'inside', withoutEnlargement: true })
        .flatten({ background: '#ffffff' })
        .jpeg({ quality: 70 })
        .toBuffer();
      return thumbnail.length <= 80_000
        ? thumbnail.toString('base64')
        : PLACEHOLDER;
    } catch {
      return PLACEHOLDER;
    }
  }
}
