/*
 * Copyright (C) 2026 Fluxer Contributors
 *
 * This file is part of Fluxer.
 *
 * Fluxer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Fluxer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
 */

import type {ChannelID, MessageID, UserID} from '@fluxer/api/src/BrandedTypes';
import {createChannelID, createMessageID} from '@fluxer/api/src/BrandedTypes';
import type {MessageDataRepository} from '@fluxer/api/src/channel/repositories/message/MessageDataRepository';
import type {MessageDeletionRepository} from '@fluxer/api/src/channel/repositories/message/MessageDeletionRepository';
import {BatchBuilder, Db, deleteOneOrMany, fetchMany, fetchOne, upsertOne} from '@fluxer/api/src/database/Cassandra';
import {Messages, MessagesByAuthor, MessagesByAuthorV2} from '@fluxer/api/src/Tables';
import * as BucketUtils from '@fluxer/snowflake/src/SnowflakeBuckets';

const SELECT_FROM_OLD_TABLE = MessagesByAuthor.select({
	where: [MessagesByAuthor.where.eq('author_id')],
	columns: ['channel_id', 'message_id'],
});

const SELECT_MESSAGE_BY_AUTHOR = MessagesByAuthorV2.select({
	where: [MessagesByAuthorV2.where.eq('author_id'), MessagesByAuthorV2.where.eq('message_id')],
	limit: 1,
});

function listMessagesByAuthorQuery(limit: number, usePagination: boolean) {
	return MessagesByAuthorV2.select({
		columns: ['channel_id', 'message_id'],
		where: usePagination
			? [MessagesByAuthorV2.where.eq('author_id'), MessagesByAuthorV2.where.lt('message_id', 'last_message_id')]
			: [MessagesByAuthorV2.where.eq('author_id')],
		orderBy: {col: 'message_id', direction: 'DESC'},
		limit,
	});
}

export class MessageAuthorRepository {
	constructor(
		private messageDataRepo: MessageDataRepository,
		private messageDeletionRepo: MessageDeletionRepository,
	) {}

	async listMessagesByAuthor(
		authorId: UserID,
		limit: number = 1000,
		lastMessageId?: MessageID,
	): Promise<Array<{channelId: ChannelID; messageId: MessageID}>> {
		const usePagination = Boolean(lastMessageId);

		const q = listMessagesByAuthorQuery(limit, usePagination);

		const results = await fetchMany<{channel_id: bigint; message_id: bigint}>(
			usePagination
				? q.bind({
						author_id: authorId,
						last_message_id: lastMessageId!,
					})
				: q.bind({
						author_id: authorId,
					}),
		);

		return results.map((r) => ({
			channelId: createChannelID(r.channel_id),
			messageId: createMessageID(r.message_id),
		}));
	}

	async deleteMessagesByAuthor(
		authorId: UserID,
		channelIds?: Array<ChannelID>,
		messageIds?: Array<MessageID>,
	): Promise<void> {
		const messagesToDelete = await this.listMessagesByAuthor(authorId);

		for (const {channelId, messageId} of messagesToDelete) {
			if (channelIds && !channelIds.includes(channelId)) continue;
			if (messageIds && !messageIds.includes(messageId)) continue;

			const message = await this.messageDataRepo.getMessage(channelId, messageId);
			if (message && message.authorId === authorId) {
				await this.messageDeletionRepo.deleteMessage(
					channelId,
					messageId,
					authorId,
					message.pinnedTimestamp || undefined,
				);
			}
		}
	}

	async hasMessageByAuthor(authorId: UserID, _channelId: ChannelID, messageId: MessageID): Promise<boolean> {
		const result = await fetchOne<{channel_id: bigint; message_id: bigint}>(
			SELECT_MESSAGE_BY_AUTHOR.bind({
				author_id: authorId,
				message_id: messageId,
			}),
		);

		return result !== null;
	}

	async backfillMessagesByAuthorIndex(authorId: UserID): Promise<void> {
		const oldMessages = await fetchMany<{channel_id: bigint; message_id: bigint}>(
			SELECT_FROM_OLD_TABLE.bind({author_id: authorId}),
		);

		if (oldMessages.length === 0) {
			return;
		}

		const BATCH_SIZE = 100;
		for (let i = 0; i < oldMessages.length; i += BATCH_SIZE) {
			const batch = new BatchBuilder();
			const chunk = oldMessages.slice(i, i + BATCH_SIZE);

			for (const row of chunk) {
				batch.addPrepared(
					MessagesByAuthorV2.upsertAll({
						author_id: authorId,
						channel_id: row.channel_id as ChannelID,
						message_id: row.message_id as MessageID,
					}),
				);
			}

			await batch.execute();
		}
	}

	async anonymizeMessage(channelId: ChannelID, messageId: MessageID, newAuthorId: UserID): Promise<void> {
		const bucket = BucketUtils.makeBucket(messageId);

		const message = await this.messageDataRepo.getMessage(channelId, messageId);
		if (!message) return;

		if (message.authorId != null) {
			await deleteOneOrMany(
				MessagesByAuthorV2.deleteByPk({
					author_id: message.authorId,
					message_id: messageId,
				}),
			);
		}

		await upsertOne(
			MessagesByAuthorV2.upsertAll({
				author_id: newAuthorId,
				channel_id: channelId,
				message_id: messageId,
			}),
		);

		await upsertOne(
			Messages.patchByPk(
				{
					channel_id: channelId,
					bucket,
					message_id: messageId,
				},
				{
					author_id: Db.set(newAuthorId),
				},
			),
		);
	}
}
