import { Notes } from '@/models/index.js';
import { activeUsersChart } from '@/services/chart/index.js';
import define from '@/server/api/define.js';
import { makePaginationQuery } from '@/server/api/common/make-pagination-query.js';
import { visibilityQuery } from '@/server/api/common/generate-visibility-query.js';
import { generateMutedUserQuery } from '@/server/api/common/generate-muted-user-query.js';
import { generateRepliesQuery } from '@/server/api/common/generate-replies-query.js';
import { generateMutedNoteQuery } from '@/server/api/common/generate-muted-note-query.js';
import { generateChannelQuery } from '@/server/api/common/generate-channel-query.js';
import { generateBlockedUserQuery } from '@/server/api/common/generate-block-query.js';
import { generateMutedRenotesQuery } from '@/server/api/common/generated-muted-renote-query.js';

export const meta = {
	tags: ['notes'],

	description: 'Returns a shuffled list of the current users notes.',

	requireCredential: true,

	res: {
		type: 'array',
		optional: false, nullable: false,
		items: {
			type: 'object',
			optional: false, nullable: false,
			ref: 'Note',
		},
	},
} as const;

export const paramDef = {
	type: 'object',
	properties: {
		limit: { type: 'integer', minimum: 1, maximum: 100, default: 10 },
		offset: { type: 'integer', minimum: 0, default: 0 },
		seed: {
			description: 'A seed for the shuffling. If the same seed is provided, the same shuffling will be used. Required for pagination to work.',
			type: 'number',
		},
	},
	required: [],
} as const;

// eslint-disable-next-line import/no-default-export
export default define(meta, paramDef, async (ps, user) => {
	//#region Construct query
	const query = Notes.createQueryBuilder('note')
		.addSelect('md5(note.id || ' + ps.seed + ')', 'shuffleorder')
		.andWhere('note.userId = :meId', { meId: user.id })
		.innerJoinAndSelect('note.user', 'user')
		.leftJoinAndSelect('user.avatar', 'avatar')
		.leftJoinAndSelect('user.banner', 'banner')
		.leftJoinAndSelect('note.reply', 'reply')
		.leftJoinAndSelect('note.renote', 'renote')
		.leftJoinAndSelect('reply.user', 'replyUser')
		.leftJoinAndSelect('replyUser.avatar', 'replyUserAvatar')
		.leftJoinAndSelect('replyUser.banner', 'replyUserBanner')
		.leftJoinAndSelect('renote.user', 'renoteUser')
		.leftJoinAndSelect('renoteUser.avatar', 'renoteUserAvatar')
		.leftJoinAndSelect('renoteUser.banner', 'renoteUserBanner')
		.orderBy('shuffleorder');

	generateChannelQuery(query, user);
	generateRepliesQuery(query, user);
	generateMutedUserQuery(query, user);
	generateMutedNoteQuery(query, user);
	generateBlockedUserQuery(query, user);
	generateMutedRenotesQuery(query, user);
	//#endregion

	const timeline = await visibilityQuery(query, user)
		.skip(ps.offset)
		.take(ps.limit)
		.getMany();

	process.nextTick(() => {
		activeUsersChart.read(user);
	});

	return await Notes.packMany(timeline, user);
});
