/**
 * Edge query functions
 */

import type { SupabaseClient } from '@supabase/supabase-js';
import type { DBGraphEdge } from '../../core/types';
import { createDebug } from '../../utils/debug';

const debug = createDebug('db:edges');

/**
 * Fetch all edges for a graph
 */
export async function fetchGraphEdges(supabase: SupabaseClient, graphId: string): Promise<DBGraphEdge[]> {
	if (!graphId) {
		throw new Error('graphId is required to fetch edges');
	}

	const { data, error } = await supabase
		.from('edges')
		.select('*')
		.eq('graph_id', graphId)
		.order('created_at', { ascending: true });

	if (error) {
		debug.error('Error fetching edges for graph %s: %O', graphId, error);
		throw error;
	}

	return (data as DBGraphEdge[]) || [];
}

/**
 * Create a new edge
 */
export async function createGraphEdge(
	supabase: SupabaseClient,
	edge: Omit<DBGraphEdge, 'id' | 'created_at' | 'updated_at'>,
): Promise<DBGraphEdge> {
	const { data, error } = await supabase.from('edges').insert(edge).select().single();

	if (error) {
		debug.error('Error creating edge: %O', error);
		throw error;
	}

	return data as DBGraphEdge;
}

/**
 * Update an edge
 */
export async function updateGraphEdge(
	supabase: SupabaseClient,
	edgeId: string,
	updates: Partial<Pick<DBGraphEdge, 'edge_type' | 'filter_condition' | 'ui_properties'>>,
): Promise<DBGraphEdge> {
	const { data, error } = await supabase
		.from('edges')
		.update({ ...updates, updated_at: new Date().toISOString() })
		.eq('id', edgeId)
		.select()
		.single();

	if (error) {
		debug.error('Error updating edge %s: %O', edgeId, error);
		throw error;
	}

	return data as DBGraphEdge;
}

/**
 * Delete an edge
 */
export async function deleteGraphEdge(supabase: SupabaseClient, edgeId: string): Promise<void> {
	const { error } = await supabase.from('edges').delete().eq('id', edgeId);

	if (error) {
		debug.error('Error deleting edge %s: %O', edgeId, error);
		throw error;
	}
}
