import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
	getUserByUsername,
	subscribe,
	unsubscribe,
	getSubscription
} from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';

/**
 * POST /api/users/[username]/subscribe  — subscribe to a user
 * DELETE /api/users/[username]/subscribe — unsubscribe
 * Requires authentication.
 */
export const POST: RequestHandler = async ({ params, locals }) => {
	if (!locals.user) error(401, 'Login required');

	const { username } = params;
	const target = await getUserByUsername(username).catch(() => null);
	if (!target) error(404, `User "${username}" not found`);
	if (locals.user.id === target.id) error(400, 'Cannot subscribe to yourself');

	try {
		await subscribe(locals.user.id, target.id);
		const sub = await getSubscription(locals.user.id, target.id);
		return json({ subscribed: true, subId: sub?.id ?? null });
	} catch (e) {
		log.error('api/users/subscribe', 'subscribe failed', { username, err: String(e) });
		error(500, 'Failed to subscribe');
	}
};

export const DELETE: RequestHandler = async ({ params, locals }) => {
	if (!locals.user) error(401, 'Login required');

	const { username } = params;
	const target = await getUserByUsername(username).catch(() => null);
	if (!target) error(404, `User "${username}" not found`);

	try {
		await unsubscribe(locals.user.id, target.id);
		return json({ subscribed: false });
	} catch (e) {
		log.error('api/users/subscribe', 'unsubscribe failed', { username, err: String(e) });
		error(500, 'Failed to unsubscribe');
	}
};
