import {
	MarkNotificationAsReadStore,
	MarkAllNotificationsAsReadStore,
	DeleteNotificationStore
} from '$houdini';
import type { GetMyNotifications$result, GetNotification$result } from '$houdini';

// Type aliases for convenience
export type Notification = NonNullable<GetMyNotifications$result['myNotifications']>[number];
export type NotificationDetail = NonNullable<GetNotification$result['notification']>;
export type NotificationEvent = NonNullable<Notification['event']>;

// Event type labels for display
const EVENT_TYPE_LABELS: Record<string, string> = {
	// Account events
	ACCOUNT_CREATED: 'Account Created',
	ACCOUNT_UPDATED: 'Account Updated',
	ACCOUNT_DEACTIVATED: 'Account Deactivated',
	ACCOUNT_REACTIVATED: 'Account Reactivated',

	// Customer events
	CUSTOMER_CREATED: 'Customer Created',
	CUSTOMER_UPDATED: 'Customer Updated',

	// Service events
	SERVICE_CREATED: 'Service Created',
	SERVICE_SCHEDULED: 'Service Scheduled',
	SERVICE_STARTED: 'Service Started',
	SERVICE_COMPLETED: 'Service Completed',
	SERVICE_CANCELLED: 'Service Cancelled',

	// Project events
	PROJECT_CREATED: 'Project Created',
	PROJECT_SCHEDULED: 'Project Scheduled',
	PROJECT_STARTED: 'Project Started',
	PROJECT_COMPLETED: 'Project Completed',
	PROJECT_CANCELLED: 'Project Cancelled',

	// Invoice events
	INVOICE_CREATED: 'Invoice Created',
	INVOICE_SENT: 'Invoice Sent',
	INVOICE_PAID: 'Invoice Paid',
	INVOICE_OVERDUE: 'Invoice Overdue',

	// Report events
	REPORT_CREATED: 'Report Created',
	REPORT_APPROVED: 'Report Approved',
	REPORT_REJECTED: 'Report Rejected',

	// Messaging events
	CONVERSATION_CREATED: 'Conversation Created',
	CONVERSATION_ARCHIVED: 'Conversation Archived',
	CONVERSATION_PARTICIPANT_ADDED: 'Participant Added',
	CONVERSATION_PARTICIPANT_REMOVED: 'Participant Removed',
	MESSAGE_SENT: 'Message Sent',
	MESSAGE_RECEIVED: 'Message Received',
	MESSAGE_READ: 'Message Read',
	MESSAGE_DELETED: 'Message Deleted'
};

// Mutation stores (singleton instances)
const markAsReadStore = new MarkNotificationAsReadStore();
const markAllAsReadStore = new MarkAllNotificationsAsReadStore();
const deleteNotificationStore = new DeleteNotificationStore();

/**
 * Mark a notification as read
 */
export async function markAsRead(id: string) {
	const result = await markAsReadStore.mutate({ id });

	if (result.errors?.length) {
		throw new Error(result.errors[0].message);
	}

	return result.data?.markNotificationAsRead;
}

/**
 * Mark all notifications as read
 */
export async function markAllAsRead() {
	const result = await markAllAsReadStore.mutate(null);

	if (result.errors?.length) {
		throw new Error(result.errors[0].message);
	}

	return result.data?.markAllNotificationsAsRead;
}

/**
 * Delete a notification
 */
export async function deleteNotification(id: string) {
	const result = await deleteNotificationStore.mutate({ id });

	if (result.errors?.length) {
		throw new Error(result.errors[0].message);
	}

	return result.data?.deleteNotification;
}

/**
 * Get event type label for display
 */
export function getEventTypeLabel(eventType: string | null | undefined): string {
	if (!eventType) return 'Event';
	return EVENT_TYPE_LABELS[eventType] ?? formatEventType(eventType);
}

/**
 * Format event type to human readable (fallback)
 */
function formatEventType(eventType: string): string {
	return eventType
		.split('_')
		.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
		.join(' ');
}

/**
 * Get action URL from notification
 * Falls back to constructing URL from entity info
 */
export function getActionUrl(notification: Notification | NotificationDetail): string | null {
	// Use explicit action URL if provided
	if (notification.actionUrl) {
		return notification.actionUrl;
	}

	// Try to construct URL from entity info
	const event = notification.event;
	if (!event?.entityType || !event?.entityId) {
		return null;
	}

	const entityType = event.entityType.toLowerCase();
	const entityId = event.entityId;

	// Map entity types to routes
	const routeMap: Record<string, string> = {
		project: `/admin/projects/${entityId}`,
		service: `/admin/services/${entityId}`,
		account: `/admin/accounts/${entityId}`,
		customer: `/admin/customers/${entityId}`,
		invoice: `/admin/invoices/${entityId}`,
		report: `/admin/reports/${entityId}`,
		conversation: `/messages/${entityId}`,
		message: `/messages` // Messages don't have direct routes
	};

	return routeMap[entityType] ?? null;
}

/**
 * Format count for display (99+ for large numbers)
 */
export function formatCount(count: number): string {
	if (count <= 0) return '';
	if (count > 99) return '99+';
	return count.toString();
}

/**
 * Get notification body preview
 */
export function getBodyPreview(body: string | null | undefined, maxLength: number = 100): string {
	if (!body) return '';

	if (body.length <= maxLength) return body;

	return body.substring(0, maxLength) + '...';
}

/**
 * Get entity type display name
 */
export function getEntityTypeLabel(entityType: string | null | undefined): string {
	if (!entityType) return '';

	const labels: Record<string, string> = {
		Project: 'Project',
		Service: 'Service',
		Account: 'Account',
		Customer: 'Customer',
		Invoice: 'Invoice',
		Report: 'Report',
		Conversation: 'Conversation',
		Message: 'Message'
	};

	return labels[entityType] ?? entityType;
}

/**
 * Get notification status label
 */
export function getStatusLabel(status: string | null | undefined): string {
	if (!status) return '';

	const labels: Record<string, string> = {
		PENDING: 'Pending',
		SENT: 'Sent',
		READ: 'Read',
		FAILED: 'Failed'
	};

	return labels[status] ?? status;
}
