import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { channel } from "./channel";
import { syncJobLifecycle } from "./syncJob.lifecycle.generated";

const builtins = (params: { companyType?: TailorAnyDBType }) => {
  const companyId = db.uuid().description("Foreign key to Company");
  return {
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "syncJobs",
        })
      : companyId,
    channelId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: channel },
        backward: "syncJobs",
      })
      .description("Foreign key to Channel"),
    direction: db.string().description("IMPORT or EXPORT"),
    status: db.enum(syncJobLifecycle.states).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"),
  };
};

type ReservedFields = keyof ReturnType<typeof builtins> | CommonReservedFields;

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

export function createSyncJobType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateSyncJobTypeParams<F>,
) {
  return db
    .type("SyncJob", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const syncJob = createSyncJobType({});
