import { z } from "zod";

import type { CreateContractContext, InferSchemaFromRefinableSchema } from "@devowl-wp/api";
import { createRefinableSchema } from "@devowl-wp/api";

const createUntranslatableSchema = createRefinableSchema({
    schema: (context: CreateContractContext) =>
        z.object({
            id: z.string(),
            text: z.string().min(1),
            serviceTemplateIdentifiers: z.array(z.string()).default([]),
            contentBlockerIdentifiers: z.array(z.string()).default([]),
        }),
    refine: (data, context: CreateContractContext) =>
        data.refine(
            ({ serviceTemplateIdentifiers, contentBlockerIdentifiers }) => {
                // Remove duplicates from arrays
                const uniqueServiceIdentifiers = [...new Set(serviceTemplateIdentifiers)];
                const uniqueContentBlockerIdentifiers = [...new Set(contentBlockerIdentifiers)];

                return (
                    uniqueServiceIdentifiers.length === serviceTemplateIdentifiers.length &&
                    uniqueContentBlockerIdentifiers.length === contentBlockerIdentifiers.length
                );
            },
            {
                error: () => context.getStore().t("Arrays must not contain duplicates."),
                path: ["serviceTemplateIdentifiers"],
            },
        ),
});

interface IUntranslatable extends InferSchemaFromRefinableSchema<typeof createUntranslatableSchema> {}

export { type IUntranslatable, createUntranslatableSchema };
