unit DatabaseSeed;

interface

uses
  Aurelius.Drivers.Interfaces,
  Aurelius.Engine.ObjectManager,
  TenantEntities;

procedure SeedDatabase(Conn: IDBConnection; const TenantId: string);

implementation

procedure CreateProducts(Conn: IDBConnection; const Names: TArray<string>);
var
  Manager: TObjectManager;
  Transaction: IDBTransaction;
  Name: string;
  Product: TProduct;
begin
  Manager := TObjectManager.Create(Conn);
  try
    // if there are already products, do not add anymore
    if Manager.Find<TProduct>.Take(1).UniqueResult <> nil then
      Exit;

    Transaction := Conn.BeginTransaction;
    try
      for Name in Names do
      begin
        Product := TProduct.Create;
        Manager.AddOwnership(Product);
        Product.Name := Name;
        Manager.Save(Product);
      end;
      Transaction.Commit;
    except
      Transaction.Rollback;
      raise;
    end;
  finally
    Manager.Free;
  end;
end;

procedure SeedMicrosoftDatabase(Conn: IDBConnection);
begin
  CreateProducts(Conn, ['Windows', 'Word', 'Excel', 'Powerpoint', 'XBox', 'OneDrive']);
end;

procedure SeedAppleDatabase(Conn: IDBConnection);
begin
  CreateProducts(Conn, ['iPhone', 'iPad', 'MacBook Air', 'MacBook Pro', 'Apple Watch', 'AppleTV+']);
end;

procedure SeedGoogleDatabase(Conn: IDBConnection);
begin
  CreateProducts(Conn, ['GMail', 'Google Docs', 'Nest Mini', 'Chromecast', 'Google Maps', 'Google Drive']);
end;

procedure SeedDatabase(Conn: IDBConnection; const TenantId: string);
begin
  if TenantId = 'microsoft' then
    SeedMicrosoftDatabase(Conn)
  else
  if TenantId = 'apple' then
    SeedAppleDatabase(Conn)
  else
  if TenantId = 'google' then
    SeedGoogleDatabase(Conn);
end;

end.
