import DbApi from '@/db/api/organizations';
import { createCrudService } from '@/services/shared/crud-service';
import { seedDefaultContentForTenant } from '@/services/content_catalog_seed';
import { withTransaction } from '@/db/with-transaction';
import type { CurrentUser } from '@/db/api/types';

const base = createCrudService(DbApi, { notFoundCode: 'organizationsNotFound' });

export default {
  ...base,
  /**
   * Creates an organization and presets its org-scoped default content (plus the
   * truly-global seed-once rows) in the same transaction. Idempotent.
   */
  async create(
    data: Parameters<typeof DbApi.create>[0],
    currentUser?: CurrentUser,
  ): Promise<void> {
    await withTransaction(async (transaction) => {
      const organization = await DbApi.create(data, { currentUser, transaction });
      await seedDefaultContentForTenant(
        { level: 'organization', organizationId: organization.id },
        transaction,
      );
    });
  },
};
