<?php

namespace CelerSearch\Factories;

use CelerSearch\DataTransfer\ServiceConfig;
use CelerSearch\Exceptions\MissingProviderException;
use CelerSearch\Exceptions\MissingServiceException;
use CelerSearch\Exceptions\MissingServiceInIndexSettings;
use CelerSearch\Repositories\ServiceRepository;
use CelerSearch\Services\BaseService;

class ServiceFactory {

	/**
	 * Creates instance from database value
	 *
	 * @param $id
	 *
	 * @return BaseService
	 * @throws MissingProviderException
	 * @throws MissingServiceException
	 */
	public static function create( $id ): BaseService {

		$repo   = new ServiceRepository();
		$record = $repo->find( $id );

		if ( ! $record ) {
			throw new MissingServiceException();
		}

		$provider = ProviderFactory::get_provider( $record->getProvider() );

		if ( ! $provider ) {
			throw new MissingProviderException();
		}

		return new $provider['model']( $record );

	}


	/**
	 * Creates a testing instance
	 *
	 * @param ServiceConfig|array $conf
	 *
	 * @return BaseService
	 * @throws MissingServiceInIndexSettings
	 */
	public static function create_for_testing( ServiceConfig|array $conf ): BaseService {

		if ( ! $conf instanceof ServiceConfig ) {

			$conf = new ServiceConfig( (object) [
				'id'         => 0,
				'name'       => isset( $conf['name'] ) ? $conf['name'] : '',
				'provider'   => isset( $conf['provider'] ) ? $conf['provider'] : '',
				'config'     => isset( $conf['config'] ) ? (object) $conf['config'] : (object) [],
				'status'     => isset( $conf['status'] ) ? $conf['status'] : '',
				'checked_at' => isset( $conf['checked_at'] ) ? $conf['checked_at'] : '',
				'created_at' => isset( $conf['created_at'] ) ? $conf['created_at'] : '',
			] );
		}

		$provider = ProviderFactory::get_provider( $conf->getProvider() );

		if ( null === $provider ) {
			throw new MissingServiceInIndexSettings();
		}

		return new $provider['model']( $conf );
	}

}