const require_objectSpread2 = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
//#region src/plus/pisellReservation/components/bookingChangeModal/utils.ts
function asRecord(value) {
	if (!value || typeof value !== "object" || Array.isArray(value)) return;
	return value;
}
function asRecordList(value) {
	if (!Array.isArray(value)) return [];
	return value.map((item) => asRecord(item)).filter(Boolean);
}
function asString(value) {
	if (value === void 0 || value === null || value === "") return;
	return String(value);
}
function asNumber(value, fallback = 0) {
	const next = Number(value);
	return Number.isFinite(next) ? next : fallback;
}
function getMetadataRecord(source) {
	var _asRecord;
	return asRecord((_asRecord = asRecord(source)) === null || _asRecord === void 0 ? void 0 : _asRecord.metadata) || {};
}
function getCustomerIdentity(orderDetail) {
	return (orderDetail === null || orderDetail === void 0 ? void 0 : orderDetail.customer_with_extra) || (orderDetail === null || orderDetail === void 0 ? void 0 : orderDetail.customer);
}
function defaultFormatHourLabel(hour) {
	const normalizedMinutes = Math.round(hour * 60);
	const wholeHours = Math.floor(normalizedMinutes / 60);
	const minutes = normalizedMinutes % 60;
	return `${String(wholeHours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`;
}
function getHourStep(hourSlots) {
	if (hourSlots.length < 2) return 1;
	const sorted = [...hourSlots].sort((a, b) => a - b);
	let minStep = Number.POSITIVE_INFINITY;
	for (let index = 1; index < sorted.length; index += 1) {
		const step = sorted[index] - sorted[index - 1];
		if (step > 0 && step < minStep) minStep = step;
	}
	return Number.isFinite(minStep) ? minStep : 1;
}
function getFallbackHourSlots() {
	return Array.from({ length: 24 }, (_, index) => index);
}
function nearestHourInSlots(hour, slots) {
	if (!Number.isFinite(hour) || slots.length === 0) return hour;
	let best = slots[0];
	let bestDist = Math.abs(hour - best);
	for (const slot of slots) {
		const distance = Math.abs(hour - slot);
		if (distance < bestDist - 1e-9) {
			bestDist = distance;
			best = slot;
		}
	}
	return best;
}
function alignBookingDraftToSlots(targetHour, durationHours, slots) {
	if (!Number.isFinite(durationHours) || durationHours < 0 || slots.length === 0) return targetHour;
	let startAligned = nearestHourInSlots(nearestHourInSlots(targetHour + durationHours, slots) - durationHours, slots);
	startAligned = nearestHourInSlots(nearestHourInSlots(startAligned + durationHours, slots) - durationHours, slots);
	return startAligned;
}
function formatDateKey(date) {
	return `${date.getFullYear()}-${`${date.getMonth() + 1}`.padStart(2, "0")}-${`${date.getDate()}`.padStart(2, "0")}`;
}
function getNormalizedDateTime(dateKey, hour) {
	const date = /* @__PURE__ */ new Date(`${dateKey}T00:00:00`);
	if (Number.isNaN(date.getTime())) return {
		date: dateKey,
		time: defaultFormatHourLabel(hour)
	};
	const minutes = Math.round(hour * 60);
	date.setMinutes(date.getMinutes() + minutes);
	return {
		date: formatDateKey(date),
		time: `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`
	};
}
function normalizeCombinedResource(value) {
	const record = asRecord(value);
	if (!record || !Array.isArray(record.resource_ids)) return;
	return {
		status: asNumber(record.status, 0),
		resource_ids: record.resource_ids.map((resourceId) => Number(resourceId)).filter((resourceId) => Number.isFinite(resourceId))
	};
}
function getItemRaw(item) {
	return asRecord(item.raw) || {};
}
function getOrderId(item) {
	const orderId = getItemRaw(item).order_id;
	if (typeof orderId === "string" || typeof orderId === "number") return orderId;
	return null;
}
function getItemResourceRecords(item) {
	const rawResources = asRecordList(getItemRaw(item).resources);
	if (rawResources.length > 0) return rawResources.map(normalizeResourceNode);
	return asRecordList(item.resources).map(normalizeResourceNode);
}
function normalizeResourceNode(resource) {
	return {
		form_id: resource.form_id,
		relation_type: resource.relation_type,
		relation_id: resource.relation_id,
		capacity: asNumber(resource.capacity, 0),
		like_status: resource.like_status,
		metadata: getMetadataRecord(resource),
		children: asRecordList(resource.children).map(normalizeResourceNode)
	};
}
function normalizeCourt(court) {
	return {
		id: court.id,
		name: court.name,
		form_id: court.form_id,
		relation_id: court.relation_id,
		relation_type: court.relation_type,
		resource_id: court.resource_id,
		capacity: asNumber(court.capacity, 0),
		like_status: court.like_status,
		metadata: getMetadataRecord(court),
		raw: asRecord(court.raw)
	};
}
function getScheduleResourceList(response) {
	if (Array.isArray(response)) return asRecordList(response);
	const record = asRecord(response);
	if (Array.isArray(record === null || record === void 0 ? void 0 : record.list)) return asRecordList(record.list);
	if (Array.isArray(record === null || record === void 0 ? void 0 : record.data)) return asRecordList(record.data);
	return [];
}
function buildScheduleResourceCourt(resource, formName) {
	const id = asString(resource.id);
	const name = asString(resource.main_field);
	if (!id || !name) return null;
	const combinedResource = normalizeCombinedResource(resource.combined_resource);
	return {
		id,
		name,
		form_id: resource.form_id,
		relation_id: resource.id,
		resource_id: resource.id,
		relation_type: "form",
		capacity: asNumber(resource.capacity, 0),
		like_status: "common",
		metadata: require_objectSpread2._objectSpread2({
			form_name: formName,
			resource_name: name
		}, combinedResource ? { combined_resource: combinedResource } : {}),
		raw: resource
	};
}
function mergeCourts(lists) {
	const merged = /* @__PURE__ */ new Map();
	for (const list of lists) for (const court of list) {
		if (!(court === null || court === void 0 ? void 0 : court.id)) continue;
		merged.set(court.id, require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, merged.get(court.id)), court), {}, { metadata: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, getMetadataRecord(merged.get(court.id))), getMetadataRecord(court)) }));
	}
	return Array.from(merged.values());
}
function buildCombinedChildren(targetCourt, resourceCourtMap) {
	const combinedResource = normalizeCombinedResource(targetCourt.metadata.combined_resource);
	if (!combinedResource || combinedResource.resource_ids.length === 0) return;
	const children = combinedResource.resource_ids.map((resourceId) => resourceCourtMap.get(String(resourceId))).filter((court) => Boolean(court)).map((court) => ({
		form_id: court.form_id,
		relation_type: court.relation_type,
		relation_id: court.relation_id,
		capacity: court.capacity,
		like_status: court.like_status,
		metadata: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, court.metadata), {}, {
			form_name: court.metadata.form_name,
			resource_name: court.metadata.resource_name
		})
	}));
	return children.length > 0 ? children : void 0;
}
function buildChangedResource(originalResource, targetCourt, resourceCourtMap) {
	const metadata = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, originalResource.metadata), targetCourt.metadata), {}, {
		form_name: targetCourt.metadata.form_name,
		resource_name: targetCourt.metadata.resource_name
	});
	const combinedResource = normalizeCombinedResource(targetCourt.metadata.combined_resource);
	if (combinedResource) metadata.combined_resource = combinedResource;
	else delete metadata.combined_resource;
	const children = buildCombinedChildren(targetCourt, resourceCourtMap);
	return require_objectSpread2._objectSpread2({
		form_id: targetCourt.form_id,
		relation_type: targetCourt.relation_type,
		relation_id: targetCourt.relation_id,
		capacity: targetCourt.capacity,
		like_status: targetCourt.like_status,
		metadata
	}, children ? { children } : {});
}
/** Convert a single event_resource record into the submit payload format. */
function normalizeEventResourceForSubmit(res) {
	const children = asRecordList(res.children).map(normalizeEventResourceForSubmit);
	return require_objectSpread2._objectSpread2({
		form_id: res.form_id,
		relation_type: res.relation_type || "form",
		relation_id: res.relation_id,
		capacity: asNumber(res.capacity, 0),
		like_status: res.like_status || "common",
		metadata: asRecord(res.metadata) || {}
	}, children.length > 0 ? { children } : {});
}
/**
* Build the resources array for submit from the authoritative event_resources list
* (sourced from orderDetail) and the per-resource court selections made in the UI.
* When a resource's selected court differs from its original relation_id the resource
* is replaced via buildChangedResource; otherwise it is emitted as-is.
*/
function buildSubmitResourcesFromEventResources(eventResources, resourceCourtIds, resourceCourtMap) {
	return eventResources.map((res, i) => {
		const selectedId = resourceCourtIds[i];
		const originalId = String(res.relation_id);
		if (selectedId && selectedId !== originalId) {
			const targetCourt = resourceCourtMap.get(selectedId);
			if (targetCourt) return buildChangedResource(normalizeResourceNode(res), targetCourt, resourceCourtMap);
		}
		return normalizeEventResourceForSubmit(res);
	});
}
function getSubmitScheduleId(raw, orderDetail) {
	var _orderDetail$bookings;
	const rawScheduleId = raw.schedule_id;
	if (rawScheduleId !== void 0 && rawScheduleId !== null && rawScheduleId !== "") return rawScheduleId;
	const rawId = raw.id;
	if (rawId === void 0 || rawId === null || rawId === "") return;
	const matchedBooking = ((orderDetail === null || orderDetail === void 0 || (_orderDetail$bookings = orderDetail.bookings) === null || _orderDetail$bookings === void 0 ? void 0 : _orderDetail$bookings.list) || []).find((booking) => String(booking === null || booking === void 0 ? void 0 : booking.id) === String(rawId));
	return matchedBooking === null || matchedBooking === void 0 ? void 0 : matchedBooking.schedule_id;
}
function buildSubmitPayload(args) {
	const { item, draft, duration, nextEndHour, currentEventResources, resourceCourtIds, resourceCourtMap, orderDetail } = args;
	const raw = getItemRaw(item);
	const rawMetadata = getMetadataRecord(raw);
	const start = getNormalizedDateTime(draft.targetDate, draft.targetHour);
	const end = getNormalizedDateTime(draft.targetDate, nextEndHour);
	const metadata = require_objectSpread2._objectSpread2({}, rawMetadata);
	const resources = buildSubmitResourcesFromEventResources(currentEventResources, resourceCourtIds, resourceCourtMap);
	return {
		id: raw.id,
		relation_id: raw.relation_id,
		like_status: raw.like_status,
		relation_type: raw.relation_type,
		is_all: asNumber(raw.is_all, 0),
		schedule_id: getSubmitScheduleId(raw, orderDetail),
		sub_type: raw.sub_type,
		select_date: draft.targetDate,
		number: raw.number,
		metadata,
		resources,
		start_date: start.date,
		start_time: start.time,
		end_date: end.date,
		end_time: end.time,
		duration: Math.max(0, Math.round(duration * 60))
	};
}
function buildCustomer(args) {
	var _contacts$phone;
	const { orderDetail, selectedCustomer, fallbackCustomerText } = args;
	if (selectedCustomer) return selectedCustomer;
	const customer = getCustomerIdentity(orderDetail);
	const contacts = orderDetail === null || orderDetail === void 0 ? void 0 : orderDetail.contacts_info;
	return {
		name: (customer === null || customer === void 0 ? void 0 : customer.display_name) || (customer === null || customer === void 0 ? void 0 : customer.nickname) || fallbackCustomerText,
		phone: (contacts === null || contacts === void 0 || (_contacts$phone = contacts.phone) === null || _contacts$phone === void 0 ? void 0 : _contacts$phone.phone) || (customer === null || customer === void 0 ? void 0 : customer.phone) || "",
		email: (contacts === null || contacts === void 0 ? void 0 : contacts.email) || (customer === null || customer === void 0 ? void 0 : customer.email) || "",
		memberId: (customer === null || customer === void 0 ? void 0 : customer.member_id) || ""
	};
}
//#endregion
exports.alignBookingDraftToSlots = alignBookingDraftToSlots;
exports.asRecord = asRecord;
exports.asRecordList = asRecordList;
exports.buildCustomer = buildCustomer;
exports.buildScheduleResourceCourt = buildScheduleResourceCourt;
exports.buildSubmitPayload = buildSubmitPayload;
exports.defaultFormatHourLabel = defaultFormatHourLabel;
exports.getFallbackHourSlots = getFallbackHourSlots;
exports.getHourStep = getHourStep;
exports.getItemResourceRecords = getItemResourceRecords;
exports.getOrderId = getOrderId;
exports.getScheduleResourceList = getScheduleResourceList;
exports.mergeCourts = mergeCourts;
exports.nearestHourInSlots = nearestHourInSlots;
exports.normalizeCourt = normalizeCourt;
