import { makePaginationQuery } from "../../common/make-pagination-query.js";
import { DriveFiles, Metas, NoteEdits, NoteFavorites, NoteReactions, Notes, UserNotePinings } from "../../../../models/index.js";
import { generateVisibilityQuery } from "../../common/generate-visibility-query.js";
import { generateMutedUserQuery } from "../../common/generate-muted-user-query.js";
import { generateBlockedUserQuery } from "../../common/generate-block-query.js";
import { getNote } from "../../common/getters.js";
import createReaction from "../../../../services/note/reaction/create.js";
import deleteReaction from "../../../../services/note/reaction/delete.js";
import createNote, { extractMentionedUsers } from "../../../../services/note/create.js";
import editNote from "../../../../services/note/edit.js";
import deleteNote from "../../../../services/note/delete.js";
import { genId } from "../../../../misc/gen-id.js";
import { PaginationHelpers } from "./pagination.js";
import { UserConverter } from "../converters/user.js";
import { UserHelpers } from "./user.js";
import { addPinned, removePinned } from "../../../../services/i/pin.js";
import { NoteConverter } from "../converters/note.js";
import { awaitAll } from "../../../../prelude/await-all.js";
import { VisibilityConverter } from "../converters/visibility.js";
import mfm from "mfm-js";
import { FileConverter } from "../converters/file.js";
import { MfmHelpers } from "./mfm.js";
import { toArray, unique } from "../../../../prelude/array.js";
import { MastoApiError } from "../middleware/catch-errors.js";
import { Cache } from "../../../../misc/cache.js";
import AsyncLock from "async-lock";
import { IdentifiableError } from "../../../../misc/identifiable-error.js";
import { IsNull } from "typeorm";
import { getStubMastoContext } from "../index.js";
export class NoteHelpers {
    static postIdempotencyCache = new Cache('postIdempotencyCache', 60 * 60);
    static postIdempotencyLocks = new AsyncLock();
    static async getDefaultReaction() {
        return Metas.createQueryBuilder().select('"defaultReaction"').execute().then((p)=>p[0].defaultReaction).then((p)=>{
            if (p != null) return p;
            throw new MastoApiError(500, "Failed to get default reaction");
        });
    }
    static async reactToNote(note, reaction, ctx) {
        const user = ctx.user;
        await createReaction(user, note, reaction).catch((e)=>{
            if (e instanceof IdentifiableError && e.id == '51c42bb4-931a-456b-bff7-e5a8a70dd298') return;
            throw e;
        });
        return getNote(note.id, user);
    }
    static async removeReactFromNote(note, ctx) {
        const user = ctx.user;
        await deleteReaction(user, note);
        return getNote(note.id, user);
    }
    static async reblogNote(note, ctx) {
        const user = ctx.user;
        const existingRenote = await Notes.findOneBy({
            userId: user.id,
            renoteId: note.id,
            text: IsNull()
        });
        if (existingRenote) return existingRenote;
        const data = {
            createdAt: new Date(),
            files: [],
            renote: note
        };
        return await createNote(user, data);
    }
    static async unreblogNote(note, ctx) {
        const user = ctx.user;
        return Notes.findBy({
            userId: user.id,
            renoteId: note.id
        }).then((p)=>p.map((n)=>deleteNote(user, n))).then((p)=>Promise.all(p)).then((_)=>getNote(note.id, user));
    }
    static async bookmarkNote(note, ctx) {
        const user = ctx.user;
        const bookmarked = await NoteFavorites.exist({
            where: {
                noteId: note.id,
                userId: user.id
            }
        });
        if (!bookmarked) {
            await NoteFavorites.insert({
                id: genId(),
                createdAt: new Date(),
                noteId: note.id,
                userId: user.id
            });
        }
        return note;
    }
    static async unbookmarkNote(note, ctx) {
        const user = ctx.user;
        return NoteFavorites.findOneBy({
            noteId: note.id,
            userId: user.id
        }).then((p)=>p !== null ? NoteFavorites.delete(p.id) : null).then((_)=>note);
    }
    static async pinNote(note, ctx) {
        const user = ctx.user;
        const pinned = await UserNotePinings.exist({
            where: {
                userId: user.id,
                noteId: note.id
            }
        });
        if (!pinned) {
            await addPinned(user, note.id);
        }
        return note;
    }
    static async unpinNote(note, ctx) {
        const user = ctx.user;
        const pinned = await UserNotePinings.exist({
            where: {
                userId: user.id,
                noteId: note.id
            }
        });
        if (pinned) {
            await removePinned(user, note.id);
        }
        return note;
    }
    static async deleteNote(note, ctx) {
        const user = ctx.user;
        if (user.id !== note.userId) throw new MastoApiError(404);
        const status = await NoteConverter.encode(note, ctx);
        await deleteNote(user, note);
        status.content = undefined;
        return status;
    }
    static async getNoteFavoritedBy(note, maxId, sinceId, minId, limit = 40, ctx) {
        if (limit > 80) limit = 80;
        const query = PaginationHelpers.makePaginationQuery(NoteReactions.createQueryBuilder("reaction"), sinceId, maxId, minId).andWhere("reaction.noteId = :noteId", {
            noteId: note.id
        }).innerJoinAndSelect("reaction.user", "user");
        return PaginationHelpers.execQueryLinkPagination(query, limit, minId !== undefined, ctx).then((reactions)=>{
            return reactions.map((p)=>p.user).filter((p)=>p);
        });
    }
    static async getNoteEditHistory(note, ctx) {
        const user = Promise.resolve(note.user ?? await UserHelpers.getUserCached(note.userId, ctx));
        const account = user.then((p)=>UserConverter.encode(p, ctx));
        const edits = await NoteEdits.find({
            where: {
                noteId: note.id
            },
            order: {
                id: "ASC"
            }
        });
        const history = [];
        const curr = {
            id: note.id,
            noteId: note.id,
            note: note,
            text: note.text,
            cw: note.cw,
            fileIds: note.fileIds,
            updatedAt: note.updatedAt ?? note.createdAt
        };
        edits.push(curr);
        let lastDate = note.createdAt;
        for (const edit of edits){
            const files = DriveFiles.packMany(edit.fileIds);
            const item = {
                account: account,
                content: MfmHelpers.toHtml(mfm.parse(edit.text ?? ''), JSON.parse(note.mentionedRemoteUsers), note.userHost).then((p)=>p ?? ''),
                created_at: lastDate.toISOString(),
                emojis: [],
                sensitive: files.then((files)=>files.length > 0 ? files.some((f)=>f.isSensitive) : false),
                spoiler_text: edit.cw ?? '',
                poll: null,
                media_attachments: files.then((files)=>files.length > 0 ? files.map((f)=>FileConverter.encode(f)) : [])
            };
            lastDate = edit.updatedAt;
            history.push(awaitAll(item));
        }
        return Promise.all(history);
    }
    static getNoteSource(note) {
        return {
            id: note.id,
            text: note.text ?? '',
            spoiler_text: note.cw ?? '',
            content_type: 'text/x.misskeymarkdown'
        };
    }
    static async getNoteRebloggedBy(note, maxId, sinceId, minId, limit = 40, ctx) {
        if (limit > 80) limit = 80;
        const user = ctx.user;
        const query = PaginationHelpers.makePaginationQuery(Notes.createQueryBuilder("note"), sinceId, maxId, minId).andWhere("note.renoteId = :noteId", {
            noteId: note.id
        }).andWhere("note.text IS NULL") // We don't want to count quotes as renotes
        .andWhere('note.hasPoll = FALSE').andWhere("note.fileIds = '{}'").innerJoinAndSelect("note.user", "user");
        generateVisibilityQuery(query, user);
        return PaginationHelpers.execQueryLinkPagination(query, limit, minId !== undefined, ctx).then((renotes)=>{
            return renotes.map((p)=>p.user).filter((p)=>p);
        });
    }
    static async getNoteDescendants(note, limit = 10, depth = 2, ctx) {
        const user = ctx.user;
        const noteId = typeof note === "string" ? note : note.id;
        const query = makePaginationQuery(Notes.createQueryBuilder("note")).andWhere("note.id IN (SELECT id FROM note_replies(:noteId, :depth, :limit))", {
            noteId,
            depth,
            limit
        });
        generateVisibilityQuery(query, user);
        if (user) {
            generateMutedUserQuery(query, user);
            generateBlockedUserQuery(query, user);
        }
        return query.getMany().then((p)=>p.reverse());
    }
    static async getNoteAncestors(rootNote, limit = 10, ctx) {
        const user = ctx.user;
        const notes = new Array;
        for(let i = 0; i < limit; i++){
            const currentNote = notes.at(-1) ?? rootNote;
            if (!currentNote.replyId) break;
            const nextNote = await getNote(currentNote.replyId, user).catch((e)=>{
                if (e.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") return null;
                throw e;
            });
            if (nextNote && await Notes.isVisibleForMe(nextNote, user?.id ?? null)) notes.push(nextNote);
            else break;
        }
        return notes.reverse();
    }
    static async createNote(request, ctx) {
        const user = ctx.user;
        const files = request.media_ids && request.media_ids.length > 0 ? DriveFiles.findByIds(request.media_ids) : [];
        const reply = request.in_reply_to_id ? await getNote(request.in_reply_to_id, user) : undefined;
        const renote = request.quote_id ? await getNote(request.quote_id, user) : undefined;
        const visibility = request.visibility ?? UserHelpers.getDefaultNoteVisibility(ctx);
        const data = {
            createdAt: new Date(),
            files: files,
            poll: request.poll ? {
                choices: request.poll.options,
                multiple: request.poll.multiple,
                expiresAt: request.poll.expires_in && request.poll.expires_in > 0 ? new Date(new Date().getTime() + request.poll.expires_in * 1000) : null
            } : undefined,
            text: request.text,
            reply: reply,
            renote: renote,
            cw: request.spoiler_text,
            visibility: visibility,
            visibleUsers: Promise.resolve(visibility).then((p)=>p === 'specified' ? this.extractMentions(request.text ?? '', ctx) : undefined)
        };
        return createNote(user, await awaitAll(data));
    }
    static async editNote(request, note, ctx) {
        const user = ctx.user;
        const files = request.media_ids && request.media_ids.length > 0 ? DriveFiles.findByIds(request.media_ids) : [];
        const data = {
            files: files,
            poll: request.poll ? {
                choices: request.poll.options,
                multiple: request.poll.multiple,
                expiresAt: request.poll.expires_in && request.poll.expires_in > 0 ? new Date(new Date().getTime() + request.poll.expires_in * 1000) : null
            } : null,
            text: request.text,
            cw: request.spoiler_text
        };
        return editNote(user, note, await awaitAll(data));
    }
    static async extractMentions(text, ctx) {
        const user = ctx.user;
        return extractMentionedUsers(user, mfm.parse(text));
    }
    static normalizeComposeOptions(body) {
        const result = {};
        if (body.status != null && body.status.trim().length > 0) result.text = body.status;
        if (body.spoiler_text != null && body.spoiler_text.trim().length > 0) result.spoiler_text = body.spoiler_text;
        if (body.visibility != null) result.visibility = VisibilityConverter.decode(body.visibility);
        if (body.language != null) result.language = body.language;
        if (body.scheduled_at != null) result.scheduled_at = new Date(Date.parse(body.scheduled_at));
        if (body.in_reply_to_id) result.in_reply_to_id = body.in_reply_to_id;
        if (body.quoted_status_id ?? body.quote_id) result.quote_id = body.quoted_status_id ?? body.quote_id;
        if (body.media_ids) result.media_ids = body.media_ids && body.media_ids.length > 0 ? toArray(body.media_ids) : undefined;
        if (body.poll) {
            result.poll = {
                expires_in: parseInt(body.poll.expires_in, 10),
                options: body.poll.options,
                multiple: !!body.poll.multiple
            };
        }
        result.sensitive = !!body.sensitive;
        return result;
    }
    static normalizeEditOptions(body) {
        const result = {};
        if (body.status != null && body.status.trim().length > 0) result.text = body.status;
        if (body.spoiler_text != null && body.spoiler_text.trim().length > 0) result.spoiler_text = body.spoiler_text;
        if (body.language != null) result.language = body.language;
        if (body.media_ids) result.media_ids = body.media_ids && body.media_ids.length > 0 ? toArray(body.media_ids) : undefined;
        if (body.poll) {
            result.poll = {
                expires_in: parseInt(body.poll.expires_in, 10),
                options: body.poll.options,
                multiple: !!body.poll.multiple
            };
        }
        result.sensitive = !!body.sensitive;
        return result;
    }
    static async getNoteOr404(id, ctx) {
        const user = ctx.user;
        return getNote(id, user).catch((_)=>{
            throw new MastoApiError(404);
        });
    }
    static async getConversationFromEvent(noteId, user) {
        const ctx = getStubMastoContext(user);
        const note = await getNote(noteId, ctx.user);
        const conversationId = note.threadId ?? note.id;
        const userIds = unique([
            note.userId
        ].concat(note.visibleUserIds).filter((p)=>p != ctx.user.id));
        const users = userIds.map((id)=>UserHelpers.getUserCached(id, ctx).catch((_)=>null));
        const accounts = Promise.all(users).then((u)=>UserConverter.encodeMany(u.filter((u)=>u), ctx));
        const res = {
            id: conversationId,
            accounts: accounts.then((u)=>u.length > 0 ? u : UserConverter.encodeMany([
                    ctx.user
                ], ctx)),
            last_status: NoteConverter.encode(note, ctx),
            unread: true
        };
        return awaitAll(res);
    }
    static fixupEventNote(note) {
        note.createdAt = note.createdAt ? new Date(note.createdAt) : note.createdAt;
        note.updatedAt = note.updatedAt ? new Date(note.updatedAt) : note.updatedAt;
        note.reply = null;
        note.renote = null;
        note.user = null;
        return note;
    }
    static getIdempotencyKey(ctx) {
        const headers = ctx.headers;
        const user = ctx.user;
        if (headers["idempotency-key"] === undefined || headers["idempotency-key"] === null) return null;
        return `${user.id}-${Array.isArray(headers["idempotency-key"]) ? headers["idempotency-key"].at(-1) : headers["idempotency-key"]}`;
    }
    static async getFromIdempotencyCache(key) {
        return this.postIdempotencyLocks.acquire(key, async ()=>{
            if (await this.postIdempotencyCache.get(key) !== undefined) {
                let i = 5;
                while((await this.postIdempotencyCache.get(key))?.status === undefined){
                    if (++i > 5) throw new Error('Post is duplicate but unable to resolve original');
                    await new Promise((resolve)=>{
                        setTimeout(resolve, 500);
                    });
                }
                return (await this.postIdempotencyCache.get(key))?.status;
            } else {
                await this.postIdempotencyCache.set(key, {});
                return undefined;
            }
        });
    }
}
