import { FieldContent, FieldContentType, isDateContent, } from "@prismicio/types-internal/lib/content" import type { Date as DateModel } from "@prismicio/types-internal/lib/customtypes" import { DiffChange, DiffOperation, } from "@prismicio/types-internal/lib/customtypes/diff" import type { NestableMock, Patch } from "../../Mock" import type { MockConfig } from "../../MockConfig" export interface DateMockConfig extends MockConfig { start?: Date end?: Date } function formatDate(date: Date): string { const formatted = date.toISOString().split("T")[0] if (!formatted) throw new Error("Something happened during Date generation.") return formatted } function random(start = new Date(2012, 0, 1), end = new Date()): string { const genDate = new Date( start.getTime() + Math.random() * (end.getTime() - start.getTime()), ) return formatDate(genDate) } export const DateMock: NestableMock = { generate(_def: DateModel, config?: DateMockConfig): FieldContent { const value = (() => { if (config?.value) return formatDate(config.value) if (config?.start && config?.end) return random(config.start, config.end) return random(new Date(2012, 0, 1), new Date()) })() return { __TYPE__: FieldContentType, type: "Date", value, } }, applyPatch(data: Patch): | { result: FieldContent | undefined } | undefined { if (data.diff.op === DiffOperation.Removed) return { result: undefined } if (data.diff.value.type === "Date") { const patched = this.patch( data.diff, isDateContent(data.content) ? data.content : undefined, data.config?.type === "Date" ? data.config : undefined, ) return { result: patched } } return }, patch( diff: DiffChange, _content: FieldContent, config?: DateMockConfig, ): FieldContent | undefined { switch (diff.op) { case DiffOperation.Removed: return case DiffOperation.Updated: case DiffOperation.Added: return this.generate(diff.value, config) } }, }