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

const builtins = (params: { userType?: TailorAnyDBType }) => {
  const userId = db.uuid().description("Foreign key to User following the source");
  return {
    userId: params.userType
      ? userId.relation({
          type: "n-1",
          toward: { type: params.userType },
          backward: "notificationSubscriptions",
        })
      : userId,
    sourceType: db
      .string()
      .description("Polymorphic discriminator identifying the followed record type"),
    sourceId: db.string().description("Polymorphic id of the followed record (no FK constraint)"),
    subscribedAt: db.datetime().description("Timestamp when the subscription was first created"),
  };
};

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

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

export function createNotificationSubscriptionType<
  const F extends Record<string, TailorAnyDBField>,
>(params: CreateNotificationSubscriptionTypeParams<F>) {
  return db
    .type("NotificationSubscription", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["userId", "sourceType", "sourceId"],
      unique: true,
      name: "notification_subscription_unique_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const notificationSubscription = createNotificationSubscriptionType({});
