import * as CANNED_RESPONSES from '../../../../../../utils/canned_responses.ts';
import { WATCH, WATCHES } from '../../../../../../models/watch.ts';
import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../../../utils/prechecks.ts';
import parse_body from '../../../../../../utils/bodyparser.ts';

export const PRECHECKS: PRECHECK_TABLE = {};

// PUT /api/users/:user_id/watches/:watch_id - Update watch
PRECHECKS.PUT = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
	const watch_id: string = meta.params?.watch_id?.toLowerCase().trim() ?? '';

	// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
	const watch: WATCH | null = watch_id.length === 49 ? await WATCHES.get(watch_id) : null;

	if (!watch) {
		return CANNED_RESPONSES.not_found();
	}

	meta.watch = watch;
	const user_owns_watch = watch.creator_id === meta.user.id;

	if (!user_owns_watch) {
		return CANNED_RESPONSES.permission_denied();
	}
}];
export async function PUT(req: Request, meta: Record<string, any>): Promise<Response> {
	const now = new Date().toISOString();

	try {
		const body = await parse_body(req);
		const updated = {
			...meta.watch,
			...body,
			id: meta.watch.id,
			timestamps: {
				created: meta.watch.timestamps.created,
				updated: now
			}
		};

		await WATCHES.update(updated);
		return Response.json(updated, {
			status: 200
		});
	} catch (err) {
		return Response.json({
			error: {
				message: (err as Error)?.message ?? 'Unknown error due to invalid data.',
				cause: (err as Error)?.cause ?? 'invalid_data'
			}
		}, {
			status: 400
		});
	}
}

// DELETE /api/users/:user_id/watches/:watch_id - Delete watch
PRECHECKS.DELETE = [
	get_session,
	get_user,
	require_user,
	async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
		const watch_id: string = meta.params?.watch_id?.toLowerCase().trim() ?? '';

		// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
		const watch: WATCH | null = watch_id.length === 49 ? await WATCHES.get(watch_id) : null;

		if (!watch) {
			return CANNED_RESPONSES.not_found();
		}

		meta.watch = watch;
		const user_owns_watch = watch.creator_id === meta.user.id;

		if (!user_owns_watch) {
			return CANNED_RESPONSES.permission_denied();
		}
	}
];
export async function DELETE(_req: Request, meta: Record<string, any>): Promise<Response> {
	await WATCHES.delete(meta.watch);

	return Response.json({
		deleted: true
	}, {
		status: 200
	});
}
