import DbApi from '@/db/api/campuses';
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: 'campusesNotFound' });

export default {
  ...base,
  /**
   * Creates a campus and presets its campus-scoped default content in the same
   * transaction. Idempotent; skipped when the campus has no organization (e.g.
   * a global-scope creator with no org context). The school's first campus is
   * seeded by SchoolsService.createWithFirstCampus, not here.
   */
  async create(
    data: Parameters<typeof DbApi.create>[0],
    currentUser?: CurrentUser,
  ): Promise<void> {
    await withTransaction(async (transaction) => {
      const campus = await DbApi.create(data, { currentUser, transaction });
      const organizationId = campus.organizationId;
      if (organizationId) {
        await seedDefaultContentForTenant(
          { level: 'campus', organizationId, campusId: campus.id },
          transaction,
        );
      }
    });
  },
};
