import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import axios from "axios";

@Injectable()
export class Msg91Provider {
  private readonly apiKey: string;
  private readonly fromEmail: string;

  constructor(private readonly config: ConfigService) {
    const apiKey = this.config.get<string>("MSG91_API_KEY");
    const fromEmail = this.config.get<string>("MSG91_FROM_EMAIL");

    if (!apiKey) {
      throw new Error("MSG91_API_KEY is missing in environment variables");
    }

    if (!fromEmail) {
      throw new Error("MSG91_FROM_EMAIL is missing in environment variables");
    }

    this.apiKey = apiKey;
    this.fromEmail = fromEmail;
  }

  async send(
    to: string,
    templateId: string,
    variables: Record<string, any>,
    replyToEmail?: string,
  ) {
    console.log(to, "to whole mail is going");
    return axios.post(
      "https://control.msg91.com/api/v5/email/send",
      {
        to: [{ email: to }],
        from: { email: this.fromEmail },
        reply_to: [
          {
            email: replyToEmail || this.fromEmail,
          },
        ],
        template_id: templateId,
        variables,
      },
      {
        headers: {
          authkey: this.apiKey,
          "Content-Type": "application/json",
        },
      },
    );
  }
}
