import axios, { AxiosError } from 'axios';
import jwt from 'jsonwebtoken';

import { MontonioClientEnvSchema } from '../schema/montonio-client-env.schema';
import { MontonioServerEnvSchema } from '../schema/montonio-server-env.schema';

const clientEnv = () =>
  MontonioClientEnvSchema.parse({
    accessKey: process.env.NEXT_PUBLIC_MONTONIO_ACCESS_KEY,
  });

const serverEnv = () =>
  MontonioServerEnvSchema.parse({
    apiUrl: process.env.MONTONIO_API_URL,
    secretKey: process.env.MONTONIO_SECRET_KEY,
  });

export class MontonioOrderHandlerService {
  public async getMontonioPaymentLink({
    notificationUrl,
    returnUrl,
    amount,
    currency,
    description,
    locale,
    merchantReference,
  }: {
    notificationUrl: string;
    returnUrl: string;
    amount: number;
    currency: string;
    description: string;
    locale: string;
    merchantReference: string;
  }) {
    const { accessKey } = clientEnv();
    const { apiUrl, secretKey } = serverEnv();

    const params = {
      accessKey,
      description,
      currency,
      amount,
      locale,
      // 15 minutes
      expiresAt: new Date(Date.now() + 15 * 60 * 1000).toISOString(),
      notificationUrl,
      returnUrl,
      askAdditionalInfo: false,
      merchantReference,
      type: 'one_time',
    };
    const token = jwt.sign(params, secretKey, {
      algorithm: 'HS256',
      expiresIn: '10m',
    });

    try {
      const { data } = await axios.post(`${apiUrl}/api/payment-links`, {
        data: token,
      });
      return data.url;
    } catch (error) {
      if (error instanceof AxiosError) {
        console.error(error.response?.data);
      }
      console.error(
        `Failed to create payment link, params=${JSON.stringify(params)}`,
        error,
      );
      throw new Error('Failed to create payment link');
    }
  }
}
