import { IExecuteFunctions, INodeExecutionData, IDataObject } from 'n8n-workflow';
import { apiRequest } from '../../../../helpers/apiRequest';
import { logger } from '../../../../helpers/logger';
import { handleApiError } from '../../../../helpers/errorHandler';

/**
 * Create Site
 *
 * POST /central/v2/sites
 *
 * @param this The n8n execution context
 * @returns Formatted API response
 */
export async function createSite(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	try {
		// Get parameters
		const siteName = this.getNodeParameter('site_name', 0) as string;
		const locationType = this.getNodeParameter('location_type', 0) as string;

		// Prepare request body
		const body: IDataObject = {
			site_name: siteName,
		};

		if (locationType === 'address') {
			const address = this.getNodeParameter('address', 0, '') as string;
			const city = this.getNodeParameter('city', 0, '') as string;
			const state = this.getNodeParameter('state', 0, '') as string;
			const country = this.getNodeParameter('country', 0, '') as string;
			const zipcode = this.getNodeParameter('zipcode', 0, '') as string;

			body.site_address = {
				address,
				city,
				state,
				country,
				zipcode,
			};
		} else if (locationType === 'geolocation') {
			const latitude = this.getNodeParameter('latitude', 0) as string;
			const longitude = this.getNodeParameter('longitude', 0) as string;

			body.geolocation = {
				latitude,
				longitude,
			};
		}

		logger.debug('monitoring:site:createSite', `Creating site with name: ${siteName}`);

		// Make API request
		const endpoint = '/central/v2/sites';
		const responseData = await apiRequest.call(this, 'POST', endpoint, body);

		logger.debug('monitoring:site:createSite', 'Successfully created site');

		// Return formatted response
		return [{ json: responseData }];
	} catch (error) {
		logger.error('monitoring:site:createSite:error', { message: error.message });
		return handleApiError.call(this, error, 'Failed to create site');
	}
}
