/**
 * Create a new customer (business logic)
 */

import type { DataSource } from '../../lib/shared/schemas/common';
import type { MutationCtx } from '../_generated/server';
import { toConvexJsonRecord } from '../lib/type_cast_helpers';
import { emitEvent } from '../workflows/triggers/emit_event';

export interface CreateCustomerArgs {
  organizationId: string;
  name?: string;
  email?: string;
  status?: 'active' | 'churned' | 'potential';
  source: DataSource;
  locale?: string;
  address?: {
    street?: string;
    city?: string;
    state?: string;
    country?: string;
    postalCode?: string;
  };
  externalId?: string | number;
  metadata?: unknown;
}

export async function createCustomer(
  ctx: MutationCtx,
  args: CreateCustomerArgs,
) {
  const customerId = await ctx.db.insert('customers', {
    organizationId: args.organizationId,
    name: args.name,
    email: args.email,
    status: args.status,
    source: args.source,
    locale: args.locale,
    address: args.address,
    externalId: args.externalId,

    metadata: toConvexJsonRecord(args.metadata),
  });

  const customer = await ctx.db.get(customerId);
  if (customer) {
    await emitEvent(ctx, {
      organizationId: args.organizationId,
      eventType: 'customer.created',
      eventData: { customer },
    });
  }

  return {
    success: true,
    customerId,
  };
}
