unit Api.ServiceImpl;

interface

uses
  XData.Server.Module, XData.Service.Common, Api.Service, Api.Database,
  System.SysUtils, System.Generics.Collections, Uni, System.JSON,
  Common.Logging, System.IniFiles, Winapi.Windows, Winapi.Messages, System.Variants,
  Winapi.ShellApi, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
  Vcl.StdCtrls, Vcl.ExtCtrls, Data.DB, uLibrary;

type
  [ServiceImplementation]
  TApiService = class(TInterfacedObject, IApiService)
  private
    FAppVersion: string;
    function GetWebClientVersion: string;

  public
    FApiDatabase: TApiDatabase;
    function TestApi(messageText: string): TJSONObject;
    constructor Create;
    destructor Destroy; override;
  end;

implementation

uses
  XData.Sys.Exceptions;

{ TApiService }
constructor TApiService.Create;
begin
  Logger.Log(1, 'TApiService.Create');
  inherited Create;
  try
    FApiDatabase := TApiDatabase.Create(nil);
  except
    on E: Exception do
    begin
      Logger.Log(2, '--Error creating TApiDatabase: ' + E.Message);
      raise;
    end;
  end;
end;


destructor TApiService.Destroy;
begin
  Logger.Log(1, 'TApiService.Destroy');
  FApiDatabase.Free;
  inherited Destroy;
end;


function TApiService.GetWebClientVersion: string;
var
  iniFile: TIniFile;
begin
  iniFile := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini'));
  try
    Result := iniFile.ReadString('Settings', 'webClientVersion', '');
  finally
    iniFile.Free;
  end;
end;

function TApiService.TestApi(messageText: string): TJSONObject;
var
  requiredVersion: string;
begin
  Logger.Log(3, 'IApiService.TestApi called');

  Result := TJSONObject.Create;
  TXDataOperationContext.Current.Handler.ManagedObjects.Add(Result);

  requiredVersion := GetWebClientVersion;

  Result.AddPair('messageEcho', messageText);
  Result.AddPair('serverTime', DateTimeToStr(Now));
  Result.AddPair('requiredWebClientVersion', requiredVersion);
  Result.AddPair('note', 'If this endpoint is reachable, JWT auth passed. Version enforcement on every API call is a separate step (middleware).');
end;



initialization
  RegisterServiceType(TApiService);


end.

