import { supabaseAdmin } from './supabase';

export type AuditAction =
	| 'member.create'
	| 'member.update'
	| 'member.delete'
	| 'member.role_change'
	| 'member.status_change'
	| 'member.invite'
	| 'event.create'
	| 'event.update'
	| 'event.delete'
	| 'event.cancel'
	| 'rsvp.create'
	| 'rsvp.update'
	| 'rsvp.cancel'
	| 'rsvp.waitlist_promote'
	| 'payment.record'
	| 'payment.delete'
	| 'document.upload'
	| 'document.delete'
	| 'document.visibility_change'
	| 'settings.update'
	| 'email.send'
	| 'auth.login'
	| 'auth.logout'
	| 'auth.password_reset';

export interface AuditLogEntry {
	userId?: string;
	userEmail?: string;
	action: AuditAction;
	resourceType?: string;
	resourceId?: string;
	details?: Record<string, unknown>;
	ipAddress?: string;
	userAgent?: string;
}

/**
 * Log an audit event to the database
 */
export async function logAudit(entry: AuditLogEntry): Promise<{ success: boolean; error?: string }> {
	try {
		const { error } = await supabaseAdmin.from('audit_logs').insert({
			user_id: entry.userId || null,
			user_email: entry.userEmail || null,
			action: entry.action,
			resource_type: entry.resourceType || null,
			resource_id: entry.resourceId || null,
			details: entry.details || {},
			ip_address: entry.ipAddress || null,
			user_agent: entry.userAgent || null
		});

		if (error) {
			console.error('Audit log error:', error);
			return { success: false, error: error.message };
		}

		return { success: true };
	} catch (error) {
		const errorMessage = error instanceof Error ? error.message : 'Unknown error';
		console.error('Audit log exception:', error);
		return { success: false, error: errorMessage };
	}
}

/**
 * Log a member-related action
 */
export async function logMemberAction(
	action: 'create' | 'update' | 'delete' | 'role_change' | 'status_change' | 'invite',
	performedBy: { id: string; email: string },
	targetMember: { id: string; email?: string },
	details?: Record<string, unknown>,
	requestInfo?: { ip?: string; userAgent?: string }
): Promise<void> {
	await logAudit({
		userId: performedBy.id,
		userEmail: performedBy.email,
		action: `member.${action}` as AuditAction,
		resourceType: 'member',
		resourceId: targetMember.id,
		details: {
			target_email: targetMember.email,
			...details
		},
		ipAddress: requestInfo?.ip,
		userAgent: requestInfo?.userAgent
	});
}

/**
 * Log an event-related action
 */
export async function logEventAction(
	action: 'create' | 'update' | 'delete' | 'cancel',
	performedBy: { id: string; email: string },
	event: { id: string; title?: string },
	details?: Record<string, unknown>,
	requestInfo?: { ip?: string; userAgent?: string }
): Promise<void> {
	await logAudit({
		userId: performedBy.id,
		userEmail: performedBy.email,
		action: `event.${action}` as AuditAction,
		resourceType: 'event',
		resourceId: event.id,
		details: {
			event_title: event.title,
			...details
		},
		ipAddress: requestInfo?.ip,
		userAgent: requestInfo?.userAgent
	});
}

/**
 * Log a payment-related action
 */
export async function logPaymentAction(
	action: 'record' | 'delete',
	performedBy: { id: string; email: string },
	payment: { id?: string; memberId: string; amount?: number },
	details?: Record<string, unknown>,
	requestInfo?: { ip?: string; userAgent?: string }
): Promise<void> {
	await logAudit({
		userId: performedBy.id,
		userEmail: performedBy.email,
		action: `payment.${action}` as AuditAction,
		resourceType: 'payment',
		resourceId: payment.id,
		details: {
			member_id: payment.memberId,
			amount: payment.amount,
			...details
		},
		ipAddress: requestInfo?.ip,
		userAgent: requestInfo?.userAgent
	});
}

/**
 * Log a document-related action
 */
export async function logDocumentAction(
	action: 'upload' | 'delete' | 'visibility_change',
	performedBy: { id: string; email: string },
	document: { id: string; title?: string },
	details?: Record<string, unknown>,
	requestInfo?: { ip?: string; userAgent?: string }
): Promise<void> {
	await logAudit({
		userId: performedBy.id,
		userEmail: performedBy.email,
		action: `document.${action}` as AuditAction,
		resourceType: 'document',
		resourceId: document.id,
		details: {
			document_title: document.title,
			...details
		},
		ipAddress: requestInfo?.ip,
		userAgent: requestInfo?.userAgent
	});
}

/**
 * Log settings update
 */
export async function logSettingsUpdate(
	performedBy: { id: string; email: string },
	category: string,
	details?: Record<string, unknown>,
	requestInfo?: { ip?: string; userAgent?: string }
): Promise<void> {
	await logAudit({
		userId: performedBy.id,
		userEmail: performedBy.email,
		action: 'settings.update',
		resourceType: 'settings',
		resourceId: category,
		details,
		ipAddress: requestInfo?.ip,
		userAgent: requestInfo?.userAgent
	});
}

/**
 * Get recent audit logs
 */
export async function getRecentAuditLogs(
	limit: number = 50,
	filters?: {
		action?: string;
		resourceType?: string;
		userId?: string;
		startDate?: string;
		endDate?: string;
	}
): Promise<{ logs: any[]; error: string | null }> {
	let query = supabaseAdmin
		.from('audit_logs')
		.select('*')
		.order('created_at', { ascending: false })
		.limit(limit);

	if (filters?.action) {
		query = query.eq('action', filters.action);
	}
	if (filters?.resourceType) {
		query = query.eq('resource_type', filters.resourceType);
	}
	if (filters?.userId) {
		query = query.eq('user_id', filters.userId);
	}
	if (filters?.startDate) {
		query = query.gte('created_at', filters.startDate);
	}
	if (filters?.endDate) {
		query = query.lte('created_at', filters.endDate);
	}

	const { data, error } = await query;

	if (error) {
		return { logs: [], error: error.message };
	}

	return { logs: data || [], error: null };
}
