import { format, parseISO, startOfWeek, endOfWeek, addDays } from 'date-fns';

/**
 * Format a date string for display.
 * Handles date-only strings (YYYY-MM-DD) without timezone shifting.
 */
export function formatDate(dateStr: string | null | undefined): string {
	if (!dateStr) return '—';

	// parseISO correctly handles date-only strings without timezone shifting
	const date = parseISO(dateStr);
	return format(date, 'MMM d, yyyy');
}

/**
 * Format a date string with time.
 */
export function formatDateTime(dateStr: string | null | undefined): string {
	if (!dateStr) return '—';

	const date = parseISO(dateStr);
	return format(date, 'MMM d, yyyy h:mm a');
}

/**
 * Get current month in YYYY-MM format.
 */
export function getCurrentMonth(): string {
	return format(new Date(), 'yyyy-MM');
}

/**
 * Get current week date range (Monday to Sunday).
 * Returns dates in YYYY-MM-DD format.
 */
export function getWeekDateRange(): { start: string; end: string } {
	const now = new Date();
	// Start of week (Monday)
	const start = startOfWeek(now, { weekStartsOn: 1 });
	// End of week (Sunday)
	const end = endOfWeek(now, { weekStartsOn: 1 });

	return {
		start: format(start, 'yyyy-MM-dd'),
		end: format(end, 'yyyy-MM-dd')
	};
}

/**
 * Get the start and end of a month in YYYY-MM-DD format.
 */
export function getMonthDateRange(month: string): { start: string; end: string } {
	const [year, monthNum] = month.split('-').map(Number);
	const startDate = new Date(year, monthNum - 1, 1);
	const endDate = new Date(year, monthNum, 0); // Last day of month

	return {
		start: format(startDate, 'yyyy-MM-dd'),
		end: format(endDate, 'yyyy-MM-dd')
	};
}
