<?php

namespace SugarCalendarBookings\Migration\Sources\Amelia\Mappers;

use SugarCalendarBookings\Migration\AbstractMapper;

/**
 * Customer Mapper.
 *
 * @since 1.3.0
 */
class CustomerMapper extends AbstractMapper {

	/**
	 * Map Amelia customer to SCB format.
	 *
	 * @since 1.3.0
	 *
	 * @param object               $raw     Raw Amelia data.
	 * @param array<string, mixed> $context Context.
	 *
	 * @return array<string, mixed>
	 */
	public function map( object $raw, array $context = [] ): array {

		$sanitized = $this->extract_and_sanitize(
			$raw,
			[
				'first_name' => [
					'source'  => 'firstName',
					'default' => '',
					'rule'    => 'string',
				],
				'last_name'  => [
					'source'  => 'lastName',
					'default' => '',
					'rule'    => 'string',
				],
				'email'      => [
					'source'  => 'email',
					'default' => '',
					'rule'    => 'email',
				],
				'phone'      => [
					'source'  => 'phone',
					'default' => '',
					'rule'    => 'string',
				],
				'note'       => [
					'source'  => 'note',
					'default' => '',
					'rule'    => 'string',
				],
				'status'     => [
					'source'  => 'status',
					'default' => 'visible',
					'rule'    => 'string',
				],
				'id'         => [
					'source'  => 'id',
					'default' => 0,
					'rule'    => 'numeric',
				],
			]
		);

		$mapped = [
			'name'       => trim( $sanitized['first_name'] . ' ' . $sanitized['last_name'] ),
			'email'      => $sanitized['email'],
			'phone'      => $sanitized['phone'] !== '' ? $sanitized['phone'] : null,
			'status'     => $this->map_entity_status( $sanitized['status'] ),
			'created_at' => current_time( 'mysql' ),
			'updated_at' => current_time( 'mysql' ),
			// Store original Amelia ID for cross-entity lookup during appointment migration.
			'_amelia_id' => (int) $sanitized['id'],
		];

		// Include notes if present.
		if ( ! empty( $sanitized['note'] ) ) {
			$mapped['notes'] = $sanitized['note'];
		}

		return $mapped;
	}
}
