import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { presignAvatarUrl, resolveAvatarUrl } from '$lib/server/minio';
import { updateUserAvatarUrl, getUserByUsername } from '$lib/server/pocketbase';
import { backendFetch } from '$lib/server/scraper';

const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp'];

/**
 * POST /api/profile/avatar
 * Body: raw image bytes (Content-Type: image/jpeg | image/png | image/webp)
 *
 * Uploads the image to MinIO via the Go backend (server-to-server, no browser
 * → MinIO direct upload), records the key in PocketBase, and returns a fresh
 * presigned GET URL for immediate display.
 *
 * Returns: { avatar_url: string | null }
 */
export const POST: RequestHandler = async ({ request, locals }) => {
	if (!locals.user) error(401, 'Not authenticated');

	const ct = request.headers.get('Content-Type') ?? '';
	// Strip parameters (e.g. "image/jpeg; charset=utf-8" → "image/jpeg")
	const mimeType = ct.split(';')[0].trim();

	if (!ALLOWED_TYPES.includes(mimeType)) {
		error(400, `Unsupported image type. Allowed: image/jpeg, image/png, image/webp`);
	}

	// Read the raw body
	const blob = await request.arrayBuffer();
	if (blob.byteLength === 0) error(400, 'Empty image body');
	if (blob.byteLength > 5 * 1024 * 1024) error(413, 'Image too large (max 5 MiB)');

	// Forward directly to Go backend — server-to-server, so internal MinIO is reachable.
	const uploadRes = await backendFetch(
		`/api/avatar-upload/${encodeURIComponent(locals.user.id)}`,
		{
			method: 'PUT',
			headers: { 'Content-Type': mimeType },
			body: blob
		}
	);
	if (!uploadRes.ok) {
		const text = await uploadRes.text().catch(() => '');
		error(uploadRes.status as 400 | 500, `Upload failed: ${text || uploadRes.statusText}`);
	}
	const { key } = (await uploadRes.json()) as { key: string };

	// Record object key in PocketBase.
	await updateUserAvatarUrl(locals.user.id, key);

	// Return a fresh presigned GET URL for immediate display.
	const avatarUrl = await presignAvatarUrl(locals.user.id);
	return json({ avatar_url: avatarUrl });
};

/**
 * GET /api/profile/avatar
 * Returns a presigned GET URL for the current user's avatar, or null if none set.
 */
export const GET: RequestHandler = async ({ locals }) => {
	if (!locals.user) error(401, 'Not authenticated');

	const record = await getUserByUsername(locals.user.username).catch(() => null);
	const avatarUrl = await resolveAvatarUrl(locals.user.id, record?.avatar_url).catch(() => null);
	return json({ avatar_url: avatarUrl });
};
