import { Injectable } from "@nestjs/common";

/**
 * Service for formatting call history data for display.
 * Handles time, duration, and phone number formatting.
 */
@Injectable()
export class SimCallHistoryFormatterService {
  /**
   * Convert HHMMSS to HH:MM:SS display format
   */
  formatTime(timeStr: string): string {
    if (!timeStr || timeStr.length < 6) return timeStr;
    const clean = timeStr.replace(/[^0-9]/g, "").padStart(6, "0");
    return `${clean.slice(0, 2)}:${clean.slice(2, 4)}:${clean.slice(4, 6)}`;
  }

  /**
   * Convert seconds to readable duration format (Xh Ym Zs)
   */
  formatDuration(seconds: number): string {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;

    if (hours > 0) {
      return `${hours}h ${minutes}m ${secs}s`;
    } else if (minutes > 0) {
      return `${minutes}m ${secs}s`;
    } else {
      return `${secs}s`;
    }
  }

  /**
   * Format Japanese phone numbers with appropriate separators
   */
  formatPhoneNumber(phone: string): string {
    if (!phone) return phone;
    const clean = phone.replace(/[^0-9+]/g, "");

    // 080-XXXX-XXXX or 070-XXXX-XXXX or 090-XXXX-XXXX format
    if (
      clean.length === 11 &&
      (clean.startsWith("080") || clean.startsWith("070") || clean.startsWith("090"))
    ) {
      return `${clean.slice(0, 3)}-${clean.slice(3, 7)}-${clean.slice(7)}`;
    }

    // 03-XXXX-XXXX format (landline)
    if (clean.length === 10 && clean.startsWith("0")) {
      return `${clean.slice(0, 2)}-${clean.slice(2, 6)}-${clean.slice(6)}`;
    }

    return clean;
  }

  /**
   * Get default month for call history queries (2 months ago)
   */
  getDefaultMonth(): string {
    const now = new Date();
    now.setMonth(now.getMonth() - 2);
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, "0");
    return `${year}-${month}`;
  }

  /**
   * Format a date to YYYY-MM format
   */
  formatYearMonth(date: Date): string {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    return `${year}-${month}`;
  }

  /**
   * Convert YYYYMM to YYYY-MM format
   */
  normalizeMonth(yearMonth: string): string {
    return `${yearMonth.slice(0, 4)}-${yearMonth.slice(4, 6)}`;
  }
}
