import * as CANNED_RESPONSES from '../../../utils/canned_responses.ts';
import * as fs from '@std/fs';
import * as path from '@std/path';
import * as media_types from '@std/media-types';

// GET /icons/:icon_path - get an icon from settings or from defaults
export async function GET(_request: Request, meta: Record<string, any>): Promise<Response> {
	const filename = meta.params.icon_path;
	if (!filename || filename.indexOf('..') !== -1) {
		return CANNED_RESPONSES.not_found();
	}

	const settings_version_exists = fs.existsSync(`./files/settings/icons/${filename}`);
	if (settings_version_exists) {
		return new Response(null, {
			status: 301,
			headers: {
				Location: `/files/settings/icons/${filename}`
			}
		});
	}

	const default_version_exists = fs.existsSync(`./icons/${filename}`);
	if (default_version_exists) {
		const extension = path.extname(filename)?.slice(1)?.toLowerCase() ?? '';

		const content_type = media_types.contentType(extension) ?? 'application/octet-stream';
		return new Response(await Deno.readFile(`./icons/${filename}`), {
			headers: {
				'Content-Type': content_type
			}
		});
	}

	return CANNED_RESPONSES.not_found();
}
