import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { channelLifecycle } from "./channel.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: "channels",
        })
      : companyId,
    type: db.string().description("Channel integration type"),
    name: db.string().description("Human-readable channel name"),
    code: db.string({ optional: true }).description("Optional short code"),
    status: db.enum(channelLifecycle.states).description("Channel lifecycle status"),
    settings: db.string({ optional: true }).description("Serialized channel settings"),
    lastSyncAt: db.date({ optional: true }).description("Last sync timestamp"),
  };
};

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

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

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

export const channel = createChannelType({});
