import { knexOwner as knex } from './knex.js';
import { curateStash } from './stashes.js';
import { HttpError } from './errors.js';

export function curateUser(user, assets = {}) {
	if (!user) {
		return null;
	}

	const curatedStashes = assets.stashes?.filter(Boolean).map((stash) => curateStash(stash)) || [];

	const curatedUser = {
		id: user.id,
		username: user.username,
		email: user.email,
		emailVerified: user.email_verified,
		identityVerified: user.identity_verified,
		avatar: `/media/avatars/${user.id}_${user.username}.png`,
		createdAt: user.created_at,
		stashes: curatedStashes,
		primaryStash: curatedStashes.find((stash) => stash.primary),
	};

	return curatedUser;
}

function whereUser(builder, userId, options = {}) {
	if (typeof userId === 'number') {
		builder.where('users.id', userId);
	}

	if (typeof userId === 'string') {
		builder.where(knex.raw('lower(users.username)'), userId.toLowerCase());

		if (options.email) {
			builder.orWhere(knex.raw('lower(users.email)'), userId.toLowerCase());
		}
	}
}

export async function fetchUser(userId, options = {}) {
	const user = await knex('users')
		.select(knex.raw('users.*, users_roles.abilities as role_abilities'))
		.modify((builder) => whereUser(builder, userId, options))
		.leftJoin('users_roles', 'users_roles.role', 'users.role')
		.groupBy('users.id', 'users_roles.role')
		.first();

	if (!user) {
		throw new HttpError(`User '${userId}' not found`, 404);
	}

	const stashes = await knex('stashes')
		.where('user_id', user.id)
		.leftJoin('stashes_meta', 'stashes_meta.stash_id', 'stashes.id');

	if (options.raw) {
		return { user, stashes };
	}

	return curateUser(user, { stashes });
}
