import { ClapAssetSource, ClapOutputType, ClapSegment, ClapSegmentStatus } from "@/types"
import { generateSeed, isValidNumber, parseOutputType, parseSegmentCategory, UUID } from "@/utils"

export function sanitizeSegment({
    id,
    parentId,
    childrenIds,
    track,
    startTimeInMs,
    endTimeInMs,
    category,
    entityId,
    workflowId,
    sceneId,
    startTimeInLines,
    endTimeInLines,
    prompt,
    label,
    outputType,
    renderId,
    status,
    assetUrl,
    assetDurationInMs,
    assetSourceType,
    assetFileFormat,
    revision,
    createdAt,
    createdBy,
    editedBy,
    outputGain,
    seed,
  }: Partial<ClapSegment> = {}): ClapSegment {
  return {
    id: typeof id === "string" ? id : UUID(),
    parentId: typeof parentId === "string" ? parentId : "",
    childrenIds: Array.isArray(childrenIds) ? childrenIds : [],
    track: isValidNumber(track) ? (track || 0) : 0,
    startTimeInMs: isValidNumber(startTimeInMs) ? (startTimeInMs || 0) : 0,
    endTimeInMs: isValidNumber(assetDurationInMs) ? (endTimeInMs || 0) : 0,
    category: parseSegmentCategory(category),
    entityId: typeof entityId === "string" ? entityId : "",
    workflowId: typeof workflowId === "string" ? workflowId : "",
    sceneId: typeof sceneId === "string" ? sceneId : "",
    startTimeInLines: isValidNumber(startTimeInLines) ? (startTimeInLines || 0) : 0,
    endTimeInLines: isValidNumber(endTimeInLines) ? (endTimeInLines || 0) : 0,
    prompt: typeof prompt === "string" ? prompt : "",
    label: typeof label === "string" ? label : "",
    outputType: parseOutputType(outputType, ClapOutputType.TEXT),
    renderId: typeof renderId === "string" ? renderId : "",
    status: typeof status === "string" ? status : ClapSegmentStatus.TO_GENERATE,
    assetUrl: typeof assetUrl === "string" ? assetUrl : "",
    assetDurationInMs: isValidNumber(assetDurationInMs) ? (assetDurationInMs || 0) : 0,
    assetSourceType: typeof assetSourceType === "string" ? assetSourceType : ClapAssetSource.EMPTY,
    assetFileFormat: typeof assetFileFormat === "string" ? assetFileFormat : "",
    revision: isValidNumber(revision) ? (revision || 0) : 0,
    createdAt: typeof createdAt === "string" ? createdAt : new Date().toISOString(),
    createdBy: typeof createdBy === "string" ? createdBy : "ai",
    editedBy: typeof editedBy === "string" ? editedBy : "ai",
    outputGain: isValidNumber(outputGain) ? (outputGain || 0) : 0,
    seed: isValidNumber(seed) ? (seed || 0) : generateSeed()
  }
}