import { importShared } from './__federation_fn_import-TbMgVVsT.js';
import { C as CASE_VALIDATORS } from './case-validators-DrReXpEg.js';

const {FeatureUtils} = await importShared('@baseplate-dev/project-builder-lib');

const BILLING_MODELS = {
  billingAccount: "BillingAccount",
  billingSubscription: "BillingSubscription"
};
const BILLING_ENUMS = {
  billingSubscriptionStatus: "BillingSubscriptionStatus"
};
function createBillingPartialDefinition(featureName, userModelName) {
  return {
    features: FeatureUtils.createPartialFeatures(featureName),
    enums: [
      {
        name: BILLING_ENUMS.billingSubscriptionStatus,
        featureRef: featureName,
        isExposed: true,
        values: [
          {
            name: "ACTIVE",
            friendlyName: "Active",
            description: "Subscription is active and billing normally"
          },
          {
            name: "TRIALING",
            friendlyName: "Trialing",
            description: "Subscription is in a free trial period"
          },
          {
            name: "PAST_DUE",
            friendlyName: "Past Due",
            description: "Payment failed but the subscription has not been canceled yet"
          },
          {
            name: "CANCELED",
            friendlyName: "Canceled",
            description: "Subscription has been canceled"
          },
          {
            name: "UNPAID",
            friendlyName: "Unpaid",
            description: "Payment retries have been exhausted and the subscription remains unpaid"
          },
          {
            name: "INCOMPLETE",
            friendlyName: "Incomplete",
            description: "Initial payment attempt failed when creating the subscription"
          },
          {
            name: "INCOMPLETE_EXPIRED",
            friendlyName: "Incomplete Expired",
            description: "First invoice was not paid within the allowed time period"
          },
          {
            name: "PAUSED",
            friendlyName: "Paused",
            description: "Subscription has been temporarily paused"
          }
        ]
      }
    ],
    models: [
      {
        name: BILLING_MODELS.billingAccount,
        featureRef: featureName,
        model: {
          fields: [
            {
              name: "id",
              type: "uuid",
              options: { defaultGeneration: "uuidv7" }
            },
            {
              name: "stripeCustomerId",
              type: "string"
            },
            {
              name: "createdAt",
              type: "dateTime",
              options: { defaultToNow: true }
            },
            {
              name: "updatedAt",
              type: "dateTime",
              options: { defaultToNow: true, updatedAt: true }
            }
          ],
          primaryKeyFieldRefs: ["id"],
          uniqueConstraints: [
            {
              fields: [{ fieldRef: "stripeCustomerId" }]
            }
          ]
        }
      },
      {
        name: BILLING_MODELS.billingSubscription,
        featureRef: featureName,
        model: {
          fields: [
            {
              name: "id",
              type: "uuid",
              options: { defaultGeneration: "uuidv7" }
            },
            {
              name: "billingAccountId",
              type: "uuid"
            },
            {
              name: "planKey",
              type: "string"
            },
            {
              name: "status",
              type: "enum",
              options: {
                enumRef: BILLING_ENUMS.billingSubscriptionStatus
              }
            },
            {
              name: "stripeSubscriptionId",
              type: "string"
            },
            {
              name: "currentPeriodStart",
              type: "dateTime"
            },
            {
              name: "currentPeriodEnd",
              type: "dateTime"
            },
            {
              name: "cancelAtPeriodEnd",
              type: "boolean",
              options: { default: "false" }
            },
            {
              name: "createdAt",
              type: "dateTime",
              options: { defaultToNow: true }
            },
            {
              name: "updatedAt",
              type: "dateTime",
              options: { defaultToNow: true, updatedAt: true }
            }
          ],
          primaryKeyFieldRefs: ["id"],
          uniqueConstraints: [
            {
              fields: [{ fieldRef: "stripeSubscriptionId" }]
            }
          ],
          relations: [
            {
              name: "billingAccount",
              references: [{ localRef: "billingAccountId", foreignRef: "id" }],
              modelRef: BILLING_MODELS.billingAccount,
              foreignRelationName: "billingSubscriptions",
              onDelete: "Cascade",
              onUpdate: "Restrict"
            }
          ]
        }
      },
      {
        name: userModelName,
        model: {
          fields: [
            {
              name: "billingAccountId",
              type: "uuid",
              isOptional: true
            }
          ],
          uniqueConstraints: [
            {
              fields: [{ fieldRef: "billingAccountId" }]
            }
          ],
          relations: [
            {
              name: "billingAccount",
              references: [{ localRef: "billingAccountId", foreignRef: "id" }],
              modelRef: BILLING_MODELS.billingAccount,
              foreignRelationName: "user",
              onDelete: "SetNull",
              onUpdate: "Restrict"
            }
          ]
        }
      }
    ]
  };
}

const {authRoleEntityType,createEntityType,definitionSchema,featureEntityType,withFix} = await importShared('@baseplate-dev/project-builder-lib');
const {z} = await importShared('zod');

const billingPlanEntityType = createEntityType("stripe/billing-plan");
const createBillingPlanSchema = definitionSchema(
  (ctx) => ctx.withEnt(
    z.object({
      id: z.string(),
      key: CASE_VALIDATORS.KEBAB_CASE.min(1),
      displayName: z.string().min(1),
      grantedRoles: z.array(
        ctx.withRef({
          type: authRoleEntityType,
          onDelete: "RESTRICT"
        })
      ).default([])
    }),
    {
      type: billingPlanEntityType,
      getNameResolver: (data) => data.key
    }
  )
);
const createStripePluginDefinitionSchema = definitionSchema((ctx) => {
  const billingPlanSchema = createBillingPlanSchema(ctx);
  return z.object({
    stripeOptions: z.object({}).prefault({}),
    billing: z.object({
      enabled: z.boolean().default(false),
      featureRef: ctx.withRef({
        type: featureEntityType,
        onDelete: "RESTRICT"
      }).optional(),
      plans: z.array(billingPlanSchema).default([]).superRefine((plans, refinementCtx) => {
        const seen = /* @__PURE__ */ new Set();
        for (const [i, plan] of plans.entries()) {
          const { key } = plan;
          if (seen.has(key)) {
            refinementCtx.addIssue({
              code: "custom",
              message: `Duplicate plan key: ${key}`,
              path: [i, "key"]
            });
            break;
          }
          seen.add(key);
        }
      })
    }).superRefine((billing, refinementCtx) => {
      if (billing.enabled && !billing.featureRef) {
        refinementCtx.addIssue({
          code: "custom",
          message: "A billing feature must be selected when billing is enabled.",
          path: ["featureRef"]
        });
      }
    }).apply(
      withFix((value) => {
        if (!value.enabled) {
          return {
            enabled: false,
            featureRef: void 0,
            plans: []
          };
        }
        return value;
      })
    )
  });
});

export { createBillingPartialDefinition as a, billingPlanEntityType as b, createStripePluginDefinitionSchema as c };
//# sourceMappingURL=plugin-definition-DC7rEk-r.js.map
