<?php

namespace RadiusTheme\RadiusBooking\ExportImport\Importers;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use RadiusTheme\RadiusBooking\ExportImport\Contracts\ImporterInterface;
use RadiusTheme\RadiusBooking\ExportImport\IdMapper;
use RadiusTheme\RadiusBooking\Models\Service;

/**
 * Class ServiceImporter
 *
 * Imports services with category_id remapping.
 *
 * @package RadiusTheme\RadiusBooking\ExportImport\Importers
 */
class ServiceImporter implements ImporterInterface {

	/**
	 * {@inheritDoc}
	 */
	public function getModuleName(): string {
		return 'service';
	}

	/**
	 * {@inheritDoc}
	 */
	public function import( array $records, IdMapper $id_mapper ): int {
		$imported = 0;

		foreach ( $records as $record ) {
			$old_id = (int) ( $record['id'] ?? 0 );
			unset( $record['id'] );
			unset( $record['created_at'], $record['updated_at'] );

			// Remap category_id.
			if ( ! empty( $record['category_id'] ) ) {
				$new_cat_id = $id_mapper->getNewId( 'category', (int) $record['category_id'] );
				$record['category_id'] = $new_cat_id ?? $record['category_id'];
			}

			// Image paths are relative strings so they can be kept.
			// listing_id is site-specific, clear it.
			$record['listing_id'] = null;

			$model = Service::create( $record );

			if ( $model && $old_id ) {
				$id_mapper->addMapping( 'service', $old_id, (int) $model->id );
				++$imported;
			}
		}

		return $imported;
	}

	/**
	 * {@inheritDoc}
	 */
	public function getDependencies(): array {
		return array( 'category' );
	}
}
