import { Injectable, Inject } from "@nestjs/common";
import { Logger } from "nestjs-pino";
import { EmailService } from "@bff/infra/email/email.service";
import { getErrorMessage } from "@bff/core/utils/error.util";

const ADMIN_EMAIL = "info@asolutions.co.jp";

export interface ApiCallLog {
  url: string;
  senddata?: Record<string, unknown> | string;
  json?: Record<string, unknown> | string;
  result: Record<string, unknown> | string;
}

@Injectable()
export class SimApiNotificationService {
  constructor(
    @Inject(Logger) private readonly logger: Logger,
    private readonly email: EmailService
  ) {}

  /**
   * Send API results notification email to admin
   */
  async sendApiResultsEmail(
    subject: string,
    apiCalls: ApiCallLog[],
    additionalInfo?: string
  ): Promise<void> {
    try {
      const lines: string[] = [];

      for (const call of apiCalls) {
        lines.push(`url: ${call.url}`);
        lines.push("");

        if (call.senddata) {
          const senddataStr =
            typeof call.senddata === "string"
              ? call.senddata
              : JSON.stringify(call.senddata, null, 2);
          lines.push(`senddata: ${senddataStr}`);
          lines.push("");
        }

        if (call.json) {
          const jsonStr =
            typeof call.json === "string"
              ? call.json
              : JSON.stringify(call.json, null, 2);
          lines.push(`json: ${jsonStr}`);
          lines.push("");
        }

        const resultStr =
          typeof call.result === "string"
            ? call.result
            : JSON.stringify(call.result, null, 2);
        lines.push(`result: ${resultStr}`);
        lines.push("");
        lines.push("---");
        lines.push("");
      }

      if (additionalInfo) {
        lines.push(additionalInfo);
      }

      await this.email.sendEmail({
        to: ADMIN_EMAIL,
        from: ADMIN_EMAIL,
        subject,
        text: lines.join("\n"),
      });

      this.logger.log("Sent API results notification email", {
        subject,
        to: ADMIN_EMAIL,
        callCount: apiCalls.length,
      });
    } catch (err) {
      this.logger.warn("Failed to send API results notification email", {
        subject,
        error: getErrorMessage(err),
      });
    }
  }

  /**
   * Send customer notification email
   */
  async sendCustomerEmail(
    to: string,
    subject: string,
    body: string
  ): Promise<void> {
    try {
      await this.email.sendEmail({
        to,
        from: ADMIN_EMAIL,
        subject,
        text: body,
      });

      this.logger.log("Sent customer notification email", {
        subject,
        to,
      });
    } catch (err) {
      this.logger.warn("Failed to send customer notification email", {
        subject,
        to,
        error: getErrorMessage(err),
      });
    }
  }

  /**
   * Build eSIM reissue customer email body
   */
  buildEsimReissueEmail(customerName: string, simNumber: string, newEid: string): string {
    return `Dear ${customerName},

This is to confirm that your request to re-issue the SIM card ${simNumber}
to the EID=${newEid} has been accepted.

Please download the SIM plan, then follow the instructions to install the APN profile.

eSIM plan download: https://www.asolutions.co.jp/uploads/pdf/esim.pdf
APN profile instructions: https://www.asolutions.co.jp/sim-card/

With best regards,
Assist Solutions Customer Support
TEL: 0120-660-470 (Mon-Fri / 10AM-6PM)
Email: ${ADMIN_EMAIL}`;
  }

  /**
   * Build physical SIM reissue customer email body
   */
  buildPhysicalSimReissueEmail(customerName: string, simNumber: string): string {
    return `Dear ${customerName},

This is to confirm that your request to re-issue the SIM card ${simNumber}
as a physical SIM has been accepted.

You will be contacted by us again as soon as details about the shipping
schedule can be disclosed (typically in 3-5 business days).

With best regards,
Assist Solutions Customer Support
TEL: 0120-660-470 (Mon-Fri / 10AM-6PM)
Email: ${ADMIN_EMAIL}`;
  }

  /**
   * Build cancellation notification email body for admin
   */
  buildCancellationAdminEmail(params: {
    customerName: string;
    simNumber: string;
    serialNumber?: string;
    cancellationMonth: string;
    registeredEmail: string;
    otherEmail?: string;
    comments?: string;
  }): string {
    return `The following SONIXNET SIM cancellation has been requested.

Customer name: ${params.customerName}
SIM #: ${params.simNumber}
Serial #: ${params.serialNumber || "N/A"}
Cancellation month: ${params.cancellationMonth}
Registered email address: ${params.registeredEmail}
Other email address: ${params.otherEmail || "N/A"}
Comments: ${params.comments || "N/A"}`;
  }
}

