/**
 * DELETE /api/v1/libs/:id/versions/:tag — remove a version and all its snippets
 */

import type { RequestHandler } from './$types';
import { getClient } from '$lib/server/db/client';
import { RepositoryService } from '$lib/server/services/repository.service';
import { VersionService } from '$lib/server/services/version.service';
import { handleServiceError, NotFoundError } from '$lib/server/utils/validation';

function getServices() {
	const db = getClient();
	return {
		repoService: new RepositoryService(db),
		versionService: new VersionService(db)
	};
}

// ---------------------------------------------------------------------------
// DELETE /api/v1/libs/:id/versions/:tag
// ---------------------------------------------------------------------------

export const DELETE: RequestHandler = ({ params }) => {
	try {
		const { repoService, versionService } = getServices();
		const repositoryId = decodeURIComponent(params.id);
		const tag = decodeURIComponent(params.tag);

		const repo = repoService.get(repositoryId);
		if (!repo) {
			throw new NotFoundError(`Repository ${repositoryId} not found`);
		}

		versionService.remove(repositoryId, tag);
		return new Response(null, { status: 204 });
	} catch (err) {
		return handleServiceError(err);
	}
};

// ---------------------------------------------------------------------------
// OPTIONS preflight
// ---------------------------------------------------------------------------

export const OPTIONS: RequestHandler = () => {
	return new Response(null, {
		status: 204,
		headers: {
			'Access-Control-Allow-Origin': '*',
			'Access-Control-Allow-Methods': 'DELETE, OPTIONS',
			'Access-Control-Allow-Headers': 'Content-Type, Authorization'
		}
	});
};
