import {
  ChatBskyConvoDefs,
  ComAtprotoAdminDefs,
  ComAtprotoRepoStrongRef,
  ToolsOzoneModerationDefs,
} from "@atproto/api";
import { Event } from "../../schemas/event";

export const transformModEventToRow = (
  eventView: ToolsOzoneModerationDefs.ModEventView
): Event => {
  return {
    id: eventView.id,
    action: `${eventView.event.$type}`, // Store event type as action
    subjectType: `${eventView.subject?.$type}`,
    subjectDid: extractSubjectDid(eventView.subject), // Extract DID based on subject type
    subjectUri: "uri" in eventView.subject ? `${eventView.subject.uri}` : null,
    subjectCid: "cid" in eventView.subject ? `${eventView.subject.cid}` : null,
    subjectBlobCids:
      "subjectBlobCids" in eventView && eventView.subjectBlobCids
        ? JSON.stringify(eventView.subjectBlobCids)
        : null,
    subjectMessageId:
      "messageId" in eventView.subject
        ? `${eventView.subject.messageId}`
        : null,
    comment:
      "comment" in eventView.event
        ? `${eventView.event.comment}` || null
        : null,
    createdAt: eventView.createdAt,
    createdBy: eventView.createdBy,
    durationInHours:
      "durationInHours" in eventView.event
        ? Number(eventView.event.durationInHours)
        : null,
    expiresAt: null, // Not explicitly available in ModEventView
    // @ts-ignore
    meta: JSON.stringify(
      Object.fromEntries(
        Object.entries(eventView.event).filter(
          ([key]) => !["comment", "durationInHours", "$type"].includes(key)
        )
      )
    ), // Stores remaining event metadata
    addedTags: eventView.event.add
      ? JSON.stringify(eventView.event.add as string[])
      : null, // Tags not explicitly in ModEventView
    removedTags: eventView.event.remove
      ? JSON.stringify(eventView.event.remove as string[])
      : null, // Tags not explicitly in ModEventView
    createLabelVals: eventView.event.createLabelVals
      ? `${eventView.event.createLabelVals}`
      : null, // Labels are not explicitly in ModEventView
    negateLabelVals: eventView.event.negateLabelVals
      ? `${eventView.event.negateLabelVals}`
      : null, // Negate labels are not explicitly in ModEventView
  };
};

/**
 * Extracts DID from different subject types
 */
const extractSubjectDid = (
  subject: ToolsOzoneModerationDefs.ModEventView["subject"]
): string => {
  if (
    ComAtprotoAdminDefs.isRepoRef(subject) ||
    ChatBskyConvoDefs.isMessageRef(subject)
  ) {
    return subject.did;
  }
  if (ComAtprotoRepoStrongRef.isMain(subject)) {
    return subject.uri.split("/").find((p) => p.startsWith("did:")) || "";
  }
  return "";
};
