import moment from "moment";

export const generateBeneficiaryId = async ({
    userName,
}: {
    userName: string;
}) => {

    const cleanName = userName
        .trim()
        .toUpperCase()
        .replace(/[^A-Z0-9]/g, "")
        .slice(0, 6);

    // timestamp part
    const timestamp = Date.now().toString().slice(-6);

    // random 3 chars
    const random = Math.random()
        .toString(36)
        .substring(2, 5)
        .toUpperCase();

    return `${cleanName}${timestamp}${random}`;
};

export const generateCashfreeVendorId = async ({
  holderName,
  bankName,
}: {
  holderName: string;
  bankName: string;
}) => {
  // 1. Sanitize strings: convert to lowercase and replace non-alphanumeric characters with underscores
  let cleanName = holderName
    .toLowerCase()
    .replace(/[^a-z0-9]/g, "_")
    .replace(/_+/g, "_")
    .replace(/^_+|_+$/g, ""); // Trim edge underscores before slicing

  // Extract exactly the first 6 characters of the sanitized username
  cleanName = cleanName.substring(0, 6).replace(/_+$/g, "");

  const cleanBank = bankName
    .toLowerCase()
    .replace(/[^a-z0-9]/g, "_")
    .replace(/_+/g, "_");

  // 2. Extract the last 6 digits of the current timestamp
  const timestamp = Date.now().toString().slice(-6);

  // 3. Construct the ID using underscores as a delimiter
  let vendorId = `${cleanName}_${cleanBank}_${timestamp}`;

  // 4. Enforce Cashfree's strict 50-character limit (just in case the bank name is massive)
  if (vendorId.length > 50) {
    // 50 max - 6 (name) - 6 (timestamp) - 2 (underscores) = 36 max characters for bank
    const allowedBankLength = 50 - (cleanName.length + timestamp.length + 2);
    const shortBank = cleanBank.substring(0, allowedBankLength);
    
    vendorId = `${cleanName}_${shortBank}_${timestamp}`;
  }

  // Trim trailing/leading underscores if any were left by the truncation logic
  return vendorId.replace(/^_+|_+$/g, "");
};

export const isHalfDay = (record: any) => {
  // Only applicable to present attendance
  if (Number(record.attendance) !== 1) {
    return false;
  }

  // No Punch In means we cannot calculate duration
  if (!record.checkIn) {
    return true;
  }

  // No Punch Out = Half Day
  if (!record.checkOut) {
    return true;
  }

  const punchIn = moment(record.checkIn);
  const punchOut = moment(record.checkOut);

  const durationInHours = moment
    .duration(punchOut.diff(punchIn))
    .asHours();

  return durationInHours < 9;
};