import { Controller, Get, Param, Res, NotFoundException } from '@nestjs/common';
import type { Response } from 'express';
import { PrismaService } from '../../../prisma/prisma.service';
import { EncryptionService } from '../../../common/services/encryption.service';

const escape = (text: string) =>
  text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');

@Controller('whatsapp/policies')
export class ShoppingPolicyController {
  constructor(
    private readonly prisma: PrismaService,
    private readonly encryption: EncryptionService,
  ) {}

  @Get(':businessId/:version/:kind')
  async page(
    @Param('businessId') businessId: string,
    @Param('version') version: string,
    @Param('kind') kind: string,
    @Res() res: Response,
  ) {
    if (!['terms', 'privacy'].includes(kind)) throw new NotFoundException();
    const integration = await this.prisma.businessIntegration.findFirst({
      where: {
        businessId,
        integrationType: 'whatsapp',
        status: 'ACTIVE',
        business: { status: 'ACTIVE' },
      },
      include: { business: { select: { name: true } } },
    });
    if (!integration) throw new NotFoundException();
    const cfg = this.encryption.decryptJson<any>(
      integration.credentialsEncrypted,
    );
    const text =
      kind === 'terms' ? cfg.shoppingTermsText : cfg.shoppingPrivacyText;
    if (
      cfg.shoppingTermsVersion !== version ||
      typeof text !== 'string' ||
      !text.trim()
    )
      throw new NotFoundException();
    const title =
      kind === 'terms'
        ? 'Shopping Terms & Conditions'
        : 'Shopping Privacy Notice';
    res.setHeader(
      'Content-Security-Policy',
      "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'",
    );
    res.setHeader('X-Content-Type-Options', 'nosniff');
    res.setHeader('Cache-Control', 'no-store');
    return res
      .type('html')
      .send(
        `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escape(title)} — ${escape(integration.business.name)}</title><style>body{font:16px/1.7 system-ui,sans-serif;color:#17212b;background:#f6f8f7;margin:0;padding:24px}main{max-width:760px;margin:24px auto;background:white;padding:32px;border-radius:16px}h1{line-height:1.25}.text{white-space:pre-wrap;overflow-wrap:anywhere}.version{color:#647067}</style></head><body><main><p>${escape(integration.business.name)}</p><h1>${title}</h1><p class="version">Version ${escape(version)}</p><div class="text">${escape(text)}</div></main></body></html>`,
      );
  }
}
