import { formatDate } from 'src/utils/common/global-utility';

/**
 * Interface defining the structure for commission details data.
 * Represents processed commission information for display or API response.
 */
interface CommissionField {
  /** Internal commission record identifier */
  id: string;

  /** Unique case identifier */
  case_uid: string;

  /** Visa case identifier (as string) */
  visa_case_id: string;

  /** Course end date (optional) */
  course_end_date?: string;

  /** Course start date (optional) */
  course_start_date?: string;

  /** Student first name */
  fname: string;

  /** Student last name */
  lname: string;

  /** Unique student identifier */
  student_uid: string;

  /** Date when visa result was determined (optional) */
  visa_result_on?: string;

  /** Visa application status (optional) */
  visa_status?: string;

  /** Formatted tuition fees (2 decimal places) */
  tuition_fees: string;

  /** Type of commission (optional) */
  commission_type?: string;

  /** Commission amount (optional) */
  commission_amount?: string;

  /** Commission percentage (optional) */
  commission_percentage?: string;

  /** Course/program name */
  course_name: string;

  /** Currency for tuition fees */
  tuition_fees_currency: string;

  /** Currency for commission amounts */
  commission_currency: string;

  /** Commission response status (optional) */
  response?: string;

  /** Date commission was processed (optional) */
  commission_date?: string;

  /** Reason for commission response (optional) */
  response_reason?: any;

  /** ID of response reason (optional) */
  response_reason_id?: string | number;

  /** Commission difference amount (optional) */
  difference?: string | number;

  /** Reason for commission difference (optional) */
  difference_reason?: any;

  /** ID of difference reason (optional) */
  difference_reason_id?: string | number;

  /** General remarks/notes (optional) */
  main_remarks?: string;

  /** Main agent commission type (optional) */
  ma_commission_type?: string;

  /** Main agent commission amount (optional) */
  ma_commission_amount?: string;

  /** Main agent commission percentage (optional) */
  ma_commission_percentage?: string;
}

/**
 * Transformer class for converting raw database commission records
 * into a standardized format for API responses or display.
 *
 * This class handles:
 * 1. Data normalization and formatting
 * 2. Type conversions (numbers to formatted strings)
 * 3. Null/undefined value handling
 * 4. Field name mapping from database to API
 *
 * @example
 * // Transform raw database records
 * const transformer = new CommissionDetailsTransformer();
 * const rawData = [{
 *   main_visa_case_id: 123,
 *   s_fname: 'John',
 *   s_lname: 'Doe',
 *   // ... other fields
 * }];
 *
 * const transformed = transformer.transform(rawData);
 * // Returns: [{
 * //   id: '123',
 * //   visa_case_id: '123',
 * //   fname: 'John',
 * //   lname: 'Doe',
 * //   // ... transformed fields
 * // }]
 */
export class CommissionDetailsTransformer {
  /**
   * Formats numeric values to strings with 2 decimal places.
   * Handles invalid numbers by returning '0.00'.
   *
   * @param value - Any value to format as a number
   * @returns Formatted string with 2 decimal places, or '0.00' for invalid inputs
   *
   * @example
   * // Returns: "123.45"
   * this.formatNumber(123.456);
   *
   * @example
   * // Returns: "0.00"
   * this.formatNumber(null);
   *
   * @example
   * // Returns: "100.00"
   * this.formatNumber("100");
   */
  private formatNumber(value: any): string {
    const num = parseFloat(value);
    return isNaN(num) ? '0.00' : num.toFixed(2);
  }

  /**
   * Transforms an array of raw database records into standardized CommissionField objects.
   * Maps database column names to cleaner API field names and applies formatting.
   *
   * @param items - Array of raw database records with commission details
   * @returns Array of transformed CommissionField objects
   *
   * @example
   * // Transform database records to API response format
   * const apiResponse = transformer.transform(databaseRows);
   */
  transform(items: Record<string, any>[]): CommissionField[] {
    return items.map((item) => {
      // Destructure with nullish coalescing for safe defaults
      const {
        main_id,
        main_visa_case_id,
        s_fname,
        s_lname,
        s_UID,
        vc_case_uid,
        cm_course_name,
        main_tuition_fees,
        main_tuition_fees_currency,
        main_commission_type,
        main_commission_percentage,
        main_commission_amount,
        main_commission_currency,
        main_commission_response_status_id,
        main_commission_date,
        main_difference,
        r_reason,
        r_id,
        dr_reason,
        dr_id,
        main_remarks,
        main_ma_commission_type,
        main_ma_commission_percentage,
        main_ma_commission_amount,
      } = item;

      return {
        // Identifiers
        id: main_visa_case_id ?? '',
        main_id: main_id ?? '', // Additional ID field not in interface - consider updating interface
        visa_case_id: String(main_visa_case_id ?? ''),
        case_uid: vc_case_uid ?? '',

        // Student information
        fname: s_fname ?? '',
        lname: s_lname ?? '',
        student_uid: s_UID ?? '',

        // Course information
        course_name: cm_course_name ?? '',

        // Financial information
        tuition_fees: this.formatNumber(main_tuition_fees),
        tuition_fees_currency: main_tuition_fees_currency ?? '',

        // Commission details
        commission_type: String(main_commission_type ?? ''),
        commission_percentage: this.formatNumber(main_commission_percentage),
        commission_amount: this.formatNumber(main_commission_amount),
        commission_currency: main_commission_currency ?? '',

        // Response and status
        response: String(main_commission_response_status_id ?? ''),
        commission_date: main_commission_date ? main_commission_date : '', // Could use formatDate() here
        response_reason: r_reason ?? null,
        response_reason_id: String(r_id || ''),

        // Difference information
        difference_reason: dr_reason ?? null,
        difference_reason_id: String(dr_id || ''),
        difference: String(main_difference || ''),

        // Additional information
        remarks: main_remarks, // Field name mismatch: main_remarks vs remarks in interface
        ma_commission_type: String(main_ma_commission_type ?? ''),
        ma_commission_percentage: main_ma_commission_percentage ?? '',
        ma_commission_amount: main_ma_commission_amount ?? '',
      };
    });
  }
}
