/**
 * Input validation helpers for the REST API.
 */

export interface ValidationError {
	field: string;
	message: string;
}

export class InvalidInputError extends Error {
	readonly code = 'INVALID_INPUT';
	constructor(
		message: string,
		public readonly errors: ValidationError[] = []
	) {
		super(message);
		this.name = 'InvalidInputError';
	}
}

export class NotFoundError extends Error {
	readonly code = 'NOT_FOUND';
	constructor(message: string) {
		super(message);
		this.name = 'NotFoundError';
	}
}

export class AlreadyExistsError extends Error {
	readonly code = 'ALREADY_EXISTS';
	constructor(message: string) {
		super(message);
		this.name = 'AlreadyExistsError';
	}
}

export class IndexingInProgressError extends Error {
	readonly code = 'INDEXING_IN_PROGRESS';
	constructor(message: string) {
		super(message);
		this.name = 'IndexingInProgressError';
	}
}

export class InvalidUrlError extends Error {
	readonly code = 'INVALID_URL';
	constructor(message: string) {
		super(message);
		this.name = 'InvalidUrlError';
	}
}

/**
 * Build a standard JSON error response body.
 */
export function errorResponse(
	error: string,
	code: string,
	status: number,
	details?: Record<string, unknown>
): Response {
	return new Response(
		JSON.stringify({ error, code, ...(details ? { details } : {}) }),
		{
			status,
			headers: { 'Content-Type': 'application/json' }
		}
	);
}

/**
 * Convert a known error type to an HTTP response.
 */
export function handleServiceError(err: unknown): Response {
	if (err instanceof NotFoundError) {
		return errorResponse(err.message, err.code, 404);
	}
	if (err instanceof AlreadyExistsError) {
		return errorResponse(err.message, err.code, 409);
	}
	if (err instanceof InvalidInputError) {
		return errorResponse(err.message, err.code, 400, {
			errors: err.errors
		});
	}
	if (err instanceof InvalidUrlError) {
		return errorResponse(err.message, err.code, 400);
	}
	if (err instanceof IndexingInProgressError) {
		return errorResponse(err.message, err.code, 409);
	}
	const message = err instanceof Error ? err.message : 'Internal server error';
	return errorResponse(message, 'INTERNAL_ERROR', 500);
}
