import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField } from "@tailor-platform/sdk";
import { company } from "./company";
import { siteLifecycle } from "./site.lifecycle.generated";

const builtins = {
  name: db.string().description("Site display name"),
  type: db
    .string()
    .description("Site type: OFFICE, WAREHOUSE, STORE, FACTORY, DISTRIBUTION_CENTER"),
  companyId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: company },
      backward: "sites",
    })
    .description("Foreign key to Company"),
  street: db.string().description("Site address street"),
  city: db.string().description("Site address city"),
  state: db.string({ optional: true }).description("Site address state/province"),
  postalCode: db.string().description("Site address postal code"),
  country: db.string().description("Site address country code"),
  timezone: db.string().description("IANA timezone identifier"),
  status: db.enum(siteLifecycle.states).description("Lifecycle status"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

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

export const site = createSiteType({});
