import crypto from "crypto";
import { ToolsOzoneModerationDefs } from "@atproto/api";
import { SubjectRow } from "../../schemas/subject";
import { RecordRow } from "../../schemas/record";
import { RepoRow } from "../../schemas/repo";

export const transformStatusToSubject = (
  status: ToolsOzoneModerationDefs.SubjectStatusView
) => {
  return {
    id: status.id,
    reviewState: status.reviewState,
    createdAt: status.createdAt,
    updatedAt: status.updatedAt,
    lastReportedAt: status.lastReportedAt || null,
    lastReviewedBy: status.lastReviewedBy || null,
    lastReviewedAt: status.lastReviewedAt || null,
    takendown: status.takendown ? 1 : 0,
    subjectRepoHandle: status.subjectRepoHandle,
    subjectBlobCids: (status.subjectBlobCids || []).join(","),
    tags: (status.tags || []).join(","),
    did: (status.subject["did"] ||
      (status.subject["uri"] as string)
        .split("/")
        .find((p) => p.startsWith("did:")) ||
      "") as string,
    recordPath: status.subject["uri"]
      ? `${status.subject["uri"]}`.split("/").slice(-2).join("/")
      : "",
    lastAppealedAt: status.lastAppealedAt || null,
    suspendUntil: status.suspendUntil || null,
    muteUntil: status.muteUntil || null,
    muteReportingUntil: status.muteReportingUntil || null,
    comment: status.comment || "",
  };
};

// Transform repo view to repo row
export function transformRepoViewToRepo(
  repoView: ToolsOzoneModerationDefs.RepoViewDetail
) {
  return {
    did: repoView.did,
    handle: repoView.handle,
    ip: `${repoView.ip}`,
    profile: JSON.stringify(repoView.relatedRecords?.[0] || {}),
    indexedAt: repoView.indexedAt,
    email: `${repoView.email}`,
    emailConfirmedAt: repoView.emailConfirmedAt || null,
    threatSignatures: JSON.stringify(repoView.threatSignatures),
    labels: JSON.stringify(repoView.labels),
  };
}

export function transformRecordViewToRecord(
  recordView: ToolsOzoneModerationDefs.RecordViewDetail
) {
  return {
    uri: recordView.uri,
    cid: recordView.cid,
    value: JSON.stringify(recordView.value),
    blobCids: JSON.stringify(recordView.blobCids),
    indexedAt: recordView.indexedAt,
    blobs: JSON.stringify(recordView.blobs),
    labels: JSON.stringify(recordView.labels),
  };
}

const hashValue = (value: string): string => {
  return crypto.createHash("sha256").update(value).digest("hex");
};

export function transformFullStatusFromDatabase(
  entry: SubjectRow & RecordRow & RepoRow
) {
  return {
    ...entry,
    profile: JSON.parse(entry.profile),
    ip: entry.ip ? hashValue(entry.ip) : "",
    email: entry.email ? hashValue(entry.email) : "",
    threatSignatures: JSON.parse(entry.threatSignatures),
    blobs: entry.blobs ? JSON.parse(entry.blobs) : entry.blobs,
    value: entry.value ? JSON.parse(entry.value) : entry.value,
  };
}
