import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { company as companyStub } from "../lib/_db_deps";
import { channel } from "./channel";

export const SYNC_JOB_STATUSES: [string, string, string, string, string] = [
  "RUNNING",
  "SUCCEEDED",
  "FAILED",
  "PARTIALLY_SUCCEEDED",
  "CANCELLED",
];

export interface CreateSyncJobTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  companyType?: TailorAnyDBType;
  channelType?: TailorAnyDBType;
}

export function createSyncJobType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateSyncJobTypeParams<F>,
) {
  return db
    .type("SyncJob", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "syncJobs",
        })
        .description("Foreign key to Company"),
      channelId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.channelType ?? channel },
          backward: "syncJobs",
        })
        .description("Foreign key to Channel"),
      direction: db.string().description("IMPORT or EXPORT"),
      status: db.enum(SYNC_JOB_STATUSES).description("Sync-job lifecycle status"),
      startedAt: db.date().description("Execution start timestamp"),
      finishedAt: db.date({ optional: true }).description("Execution end timestamp"),
      processedCount: db.int().description("Processed count"),
      successCount: db.int().description("Succeeded count"),
      errorCount: db.int().description("Error count"),
      errorSummary: db.string({ optional: true }).description("Latest error summary"),
      retryOfSyncJobId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: "self" },
          backward: "retrySyncJobs",
        })
        .description("Optional retried sync job"),
      context: db.string({ optional: true }).description("Serialized execution context"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const syncJob = createSyncJobType({});
