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

export const CHANNEL_STATUSES: [string, string, string] = ["DRAFT", "ACTIVE", "INACTIVE"];

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

export function createChannelType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateChannelTypeParams<F>,
) {
  return db
    .type("Channel", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "channels",
        })
        .description("Foreign key to Company"),
      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(CHANNEL_STATUSES).description("Channel lifecycle status"),
      settings: db.string({ optional: true }).description("Serialized channel settings"),
      lastSyncAt: db.date({ optional: true }).description("Last sync timestamp"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const channel = createChannelType({});
