<?php

namespace RadiusTheme\RadiusBooking\ExportImport;

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

use RadiusTheme\RadiusBooking\Core\Container\Container;

/**
 * Class ImportBuilder
 *
 * Fluent builder for import operations.
 *
 * Usage:
 *   Import::module('appointment')->import($records);
 *   Import::fromFile('/path/to/export.json')->import();
 *
 * @package RadiusTheme\RadiusBooking\ExportImport
 */
class ImportBuilder {

	/**
	 * Module name to import.
	 *
	 * @var string|null
	 */
	private ?string $module_name = null;

	/**
	 * File path for file-based import.
	 *
	 * @var string|null
	 */
	private ?string $file_path = null;

	/**
	 * Set a single module.
	 *
	 * @param string $module Module name.
	 *
	 * @return self
	 */
	public function module( string $module ): self {
		$this->module_name = $module;
		return $this;
	}

	/**
	 * Set file path for import.
	 *
	 * @param string $path Path to JSON file.
	 *
	 * @return self
	 */
	public function fromFile( string $path ): self {
		$this->file_path = $path;
		return $this;
	}

	/**
	 * Execute the import.
	 *
	 * @param array $records Records to import (for single module).
	 *
	 * @return array Import results.
	 */
	public function import( array $records = array() ): array {
		$service = Container::resolve( ExportImportService::class );

		// File-based import.
		if ( $this->file_path ) {
			if ( ! file_exists( $this->file_path ) ) {
				return array(
					'success' => false,
					'errors'  => array( 'File not found: ' . $this->file_path ),
				);
			}

			$json = file_get_contents( $this->file_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
			$data = json_decode( $json, true );

			if ( json_last_error() !== JSON_ERROR_NONE ) {
				return array(
					'success' => false,
					'errors'  => array( 'Invalid JSON: ' . json_last_error_msg() ),
				);
			}

			return $service->importFromData( $data );
		}

		// Single module import.
		if ( $this->module_name && ! empty( $records ) ) {
			$id_mapper = new IdMapper( IdMapper::generateSessionKey() );
			$imported  = $service->importBatch( $this->module_name, $records, $id_mapper );
			$id_mapper->cleanup();

			return array(
				'success' => true,
				'results' => array( $this->module_name => $imported ),
			);
		}

		return array(
			'success' => false,
			'errors'  => array( 'No module or file specified.' ),
		);
	}
}
