import { action, computed, reaction, runInAction } from "mobx";

import type { WpRestEndpointWithMultilingualSection } from "@devowl-wp/multilingual";
import type { PostStatus } from "@devowl-wp/utils";
import { AbstractPost, ClientModel } from "@devowl-wp/utils";

import { RootStore } from "../store/stores.js";
import { request } from "../utils/request.js";

import type { BlockerCollection } from "./blockerCollection.js";
import type { BlockerTemplate } from "./blockerTemplate.js";
import type { BlockerMeta } from "../types/blocker.js";

@ClientModel.annotate({
    keyId: "id",
    namespace: "wp/v2",
    request,
    create: {
        path: "/rcb-blocker",
    },
    patch: {
        path: "/rcb-blocker/:id",
    },
    delete: {
        path: "/rcb-blocker/:id",
    },
})
class BlockerModel extends AbstractPost<
    BlockerCollection,
    BlockerMeta,
    {
        usedTemplate: false | BlockerTemplate["data"];
    } & WpRestEndpointWithMultilingualSection
> {
    @computed
    public get templateModel() {
        return RootStore.get.cookieStore.templatesBlocker.get(this.data.meta?.presetId);
    }

    @computed
    public get rules() {
        return this.data?.meta.rules.split("\n");
    }

    @computed
    public get tcfVendors() {
        // In lite version this can be `null`
        if (!this.data?.meta.tcfVendors) {
            return [];
        }

        return this.data.meta.tcfVendors.split(",").filter(Boolean).map(Number);
    }

    @computed
    public get tcfPurposes() {
        // In lite version this can be `null`
        if (!this.data?.meta.tcfPurposes) {
            return [];
        }

        return this.data.meta.tcfPurposes.split(",").filter(Boolean).map(Number);
    }

    @computed
    public get services() {
        return this.data?.meta.services.split(",").filter(Boolean).map(Number);
    }

    @computed
    public get rootStore() {
        return this.collection.store.rootStore;
    }

    @computed
    public get isUpdateAvailable() {
        for (const { post_id } of this.rootStore.optionStore.templateNeedsUpdate) {
            if (post_id === this.data.id) {
                return true;
            }
        }
        return false;
    }

    public constructor(collection: BlockerModel["collection"], data: Partial<BlockerModel["data"]> = {}) {
        super(collection, data);

        reaction(
            () => this.data?.usedTemplate,
            (template) =>
                runInAction(() => {
                    if (template) {
                        RootStore.get.cookieStore.addBlockerTemplates([template]);
                    }
                }),
            { fireImmediately: true },
        );
    }

    @action
    public setName(name: string) {
        this.data.title.raw = name;
    }

    @action
    public setStatus(status: PostStatus) {
        this.data.status = status;
    }

    @action
    public setDescription(purpose: string) {
        this.data.content.raw = purpose;
    }

    @action
    public setMeta(meta: BlockerModel["data"]["meta"]) {
        this.data.meta = meta;
    }

    public transformDataForPatch(): any {
        const data = super.transformDataForPatch();
        return {
            title: data.title,
            content: data.content,
            status: data.status,
            meta: data.meta,
            slug: data.title,
        };
    }

    public afterPatch() {
        this.collection.store.blockers.store.rootStore.optionStore.fetchCurrentRevision();
    }

    public afterDelete() {
        this.collection.store.blockers.store.rootStore.optionStore.fetchCurrentRevision();
    }

    public afterPersist() {
        this.collection.store.blockers.store.rootStore.optionStore.fetchCurrentRevision();
    }
}

export { BlockerModel };
