import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';

export const GET: RequestHandler = ({ url }) => {
	const rawPath = url.searchParams.get('path') ?? os.homedir();
	const target = path.resolve(rawPath);

	let entries: { name: string; path: string; isGitRepo: boolean }[] = [];
	let error: string | null = null;
	let resolved = target;

	try {
		const items = fs.readdirSync(target, { withFileTypes: true });
		entries = items
			.filter((d) => d.isDirectory() && !d.name.startsWith('.'))
			.map((d) => {
				const full = path.join(target, d.name);
				const isGitRepo = fs.existsSync(path.join(full, '.git'));
				return { name: d.name, path: full, isGitRepo };
			})
			.sort((a, b) => {
				// git repos first, then alphabetical
				if (a.isGitRepo !== b.isGitRepo) return a.isGitRepo ? -1 : 1;
				return a.name.localeCompare(b.name);
			});
	} catch (e) {
		error = (e as NodeJS.ErrnoException).code === 'EACCES' ? 'Permission denied' : 'Path not found';
	}

	const parent = target !== path.parse(target).root ? path.dirname(target) : null;

	return json({ path: resolved, parent, entries, error });
};
