import { Database } from 'bun:sqlite';

const dbName = './db/strimserve.db';

// Create a new database object and initialize it with the schema
const db = new Database(dbName);

export function getStreams() {
	const indexData = db
		.prepare(
			'SELECT id, stream_date, title, tags, length_seconds ' + 'FROM Stream ORDER BY id DESC'
		)
		.all();
	indexData.forEach((stream) => {
		stream['stream_date'] = Date.parse(stream['stream_date']);
		stream['tags'] = JSON.parse(stream['tags']);
	});
	return indexData;
}

export function getStreamInfo(streamId) {
	const streamData = db
		.prepare(
			'SELECT id, stream_date, filename, ' +
				'format, title, description, tags, ' +
				'length_seconds, tracks FROM Stream ' +
				'WHERE id = ?'
		)
		.get(streamId);
	streamData['stream_date'] = Date.parse(streamData['stream_date']);
	streamData['tracks'] = JSON.parse(streamData['tracks']);
	streamData['tags'] = JSON.parse(streamData['tags']);
	streamData['tracks_num'] = streamData['tracks'].length;
	return streamData;
}
