/**
 * GET    /api/v1/libs/:id  — get a single repository
 * PATCH  /api/v1/libs/:id  — update repository metadata
 * DELETE /api/v1/libs/:id  — delete a repository
 */
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getClient } from '$lib/server/db/client';
import { RepositoryService } from '$lib/server/services/repository.service';
import { handleServiceError } from '$lib/server/utils/validation';

function getService() {
	return new RepositoryService(getClient());
}

export const GET: RequestHandler = ({ params }) => {
	try {
		const service = getService();
		const id = decodeURIComponent(params.id);
		const repo = service.get(id);
		if (!repo) {
			return json({ error: 'Repository not found', code: 'NOT_FOUND' }, { status: 404 });
		}
		const versions = service.getVersions(id);
		const { githubToken: _token, ...safeRepo } = repo;
		return json({ ...safeRepo, versions });
	} catch (err) {
		return handleServiceError(err);
	}
};

export const PATCH: RequestHandler = async ({ params, request }) => {
	try {
		const service = getService();
		const id = decodeURIComponent(params.id);
		const body = await request.json();
		const updated = service.update(id, {
			title: body.title,
			description: body.description,
			branch: body.branch,
			githubToken: body.githubToken
		});
		const { githubToken: _token, ...safeUpdated } = updated;
		return json(safeUpdated);
	} catch (err) {
		return handleServiceError(err);
	}
};

export const DELETE: RequestHandler = ({ params }) => {
	try {
		const service = getService();
		const id = decodeURIComponent(params.id);
		service.remove(id);
		return new Response(null, { status: 204 });
	} catch (err) {
		return handleServiceError(err);
	}
};

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