/*
 * SPDX-FileCopyrightText: syuilo and misskey-project
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import { Inject, Injectable } from '@nestjs/common';
import { Endpoint } from '@/server/api/endpoint-base.js';
import { MiAutoRemovalCondition } from '@/models/_.js';
import type { AutoRemovalConditionRepository, UsersRepository } from '@/models/_.js';
import { DI } from '@/di-symbols.js';
import { UserEntityService } from '@/core/entities/UserEntityService.js';
import { GlobalEventService } from '@/core/GlobalEventService.js';

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

	requireCredential: true,
	requireRolePolicy: 'canUseAutoNoteRemoval',

	kind: 'write:account',

	errors: {
		noSuchUser: {
			message: 'No such user.',
			code: 'NO_SUCH_USER',
			id: 'fcd2eef9-a9b2-4c4f-8624-038099e90aa5',
		},
	},

	res: {
		type: 'object',
		ref: 'MeDetailed',
	},
} as const;

export const paramDef = {
	type: 'object',
	properties: {
		active: { type: 'boolean' },
		deleteAfter: { type: 'number' },
		noPiningNotes: { type: 'boolean' },
		noSpecifiedNotes: { type: 'boolean' },
	},
} as const;

@Injectable()
export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
	constructor(
		@Inject(DI.autoRemovalConditionRepository)
		private autoRemovalConditionRepository: AutoRemovalConditionRepository,

		@Inject(DI.usersRepository)
		private usersRepository: UsersRepository,

		private userEntityService: UserEntityService,
		private globalEventService: GlobalEventService,
	) {
		super(meta, paramDef, async (ps, me) => {
			await this.usersRepository.update(me.id, { autoRemoval: ps.active });
			let updates = await this.autoRemovalConditionRepository.findOneBy({ userId: me.id });
			if (updates === null) {
				updates = new MiAutoRemovalCondition({
					userId: me.id,
					deleteAfter: 7,
					noPiningNotes: false,
					noSpecifiedNotes: false,
				});
			}
			if (ps.deleteAfter !== undefined) updates.deleteAfter = ps.deleteAfter;
			if (ps.noPiningNotes !== undefined) updates.noPiningNotes = ps.noPiningNotes;
			if (ps.noSpecifiedNotes !== undefined) updates.noSpecifiedNotes = ps.noSpecifiedNotes;
			await this.autoRemovalConditionRepository.save(updates);

			const iObj = await this.userEntityService.pack(me.id, me, {
				schema: 'MeDetailed',
				includeSecrets: true,
			});

			// Publish meUpdated event
			this.globalEventService.publishMainStream(me.id, 'meUpdated', iObj);

			return iObj;
		});
	}
}
