"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateRepositoriesModule = generateRepositoriesModule;
const Generator = __importStar(require("@postxl/generator"));
const schema_1 = require("@postxl/schema");
const utils_1 = require("@postxl/utils");
function generateRepositoriesModule(context) {
    const imports = Generator.ImportGenerator
        //
        .from(context.repositories.module.location)
        .add(context.database.module.moduleClass) // NOSONAR
        .add(context.repositories.dataService)
        .addImport({ items: [Generator.toTypeName('DynamicModule')], from: Generator.toPackageName('@nestjs/common') });
    let useInMemory = false;
    const providers = new Map();
    for (const model of context.models.values()) {
        switch (model.repository.kind) {
            case 'NoRepository':
                break;
            case 'InMemory':
                imports.add(model.repository);
                providers.set(model.name, `${model.repository.name}`);
                break;
            case 'DatabaseDirect':
            case 'DatabaseCached':
                imports.add(model.repository).add(model.repository.inMemoryVersion);
                providers.set(model.name, `{
            provide: ${model.repository.name},
            useClass: useInMemory ? ${model.repository.inMemoryVersion.name} : ${model.repository.name},
          }`);
                useInMemory = true;
                break;
            default:
                throw new utils_1.ExhaustiveSwitchCheck(model.repository);
        }
    }
    // We define the user repository provider explicitly as a factory provider to ensure that the init method is called
    providers.set(schema_1.standardModelName_User, 'userRepositoryProvider');
    const userModel = context.models.get(schema_1.standardModelName_User);
    let userRepositoryProvider = '';
    switch (userModel.repository.kind) {
        case 'NoRepository':
            providers.delete(schema_1.standardModelName_User);
            break;
        case 'InMemory':
            imports.addImport({
                items: [Generator.toTypeName('FactoryProvider')],
                from: Generator.toPackageName('@nestjs/common'),
            });
            userRepositoryProvider = `const userRepositoryProvider: FactoryProvider<UserRepository> = {
        provide: UserRepository,
        useFactory: async () => {
          const repository =  new ${userModel.repository.name}()
          await repository.init(false)
          return repository
        },
      }`;
            break;
        case 'DatabaseDirect':
        case 'DatabaseCached':
            imports.add(context.database.service);
            userRepositoryProvider = `const userRepositoryProvider = {
        provide: UserRepository,
        inject: [${context.database.service.name}],
        useFactory: async (dbService: ${context.database.service.name}) => {
          const repository =  useInMemory ? new ${userModel.repository.inMemoryVersion.name}() : new ${userModel.repository.name}(dbService)
          await repository.init(false)
          return repository
        },
      }`;
            useInMemory = true;
            break;
        default:
            throw new utils_1.ExhaustiveSwitchCheck(userModel.repository);
    }
    // In case all repositories are in memory, we don't need to pass the useInMemory option
    const useInMemoryVariable = useInMemory ? 'useInMemory' : 'useInMemory: _useInMemory';
    return /* ts */ `
${imports.generate()}

type ${context.repositories.module.name}Options = {
  /**
   * Configures if all repositories should be in memory.
   * This is useful for testing and development.
   */
  useInMemory: boolean
}

export class ${context.repositories.module.name} {
  public static forRoot({${useInMemoryVariable}}: ${context.repositories.module.name}Options): DynamicModule {
    ${userRepositoryProvider}

    const providers = [
      DataService,

      ${Array.from(providers.values()).join(',\n')}
    ]

    return {
      module: ${context.repositories.module.name},
      global: true,
      imports: [${context.database.module.moduleClass.name}],
      providers,
      exports: providers,
    }
  }
}
`;
}
//# sourceMappingURL=repository-module.generator.js.map