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

/**
 * Update Site
 *
 * PATCH /central/v2/sites/{site_id}
 *
 * @param this The n8n execution context
 * @returns Formatted API response
 */
export async function updateSite(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	try {
		// Get parameters
		const siteId = this.getNodeParameter('site_id', 0) as number;
		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:updateSite', `Updating site with ID: ${siteId}`);

		// Make API request
		const endpoint = `/central/v2/sites/${siteId}`;
		const responseData = await apiRequest.call(this, 'PATCH', endpoint, body);

		logger.debug('monitoring:site:updateSite', 'Successfully updated site');

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