namespace HanaTui.Hana;

/// <summary>
/// Builds the SQL / shell command strings for each operation.
/// All SQL is built here; nothing else constructs query strings.
/// </summary>
public static class SqlQueryBuilder
{
    public static string ExportSchema(string schema, string exportDir, int threads)
        => $"EXPORT \"{schema}\".\"*\" AS BINARY INTO '{exportDir}' WITH REPLACE THREADS {threads} NO DEPENDENCIES;";

    public static string ImportSchema(string schema, string importDir, int threads, bool replace)
    {
        var opts = replace ? "REPLACE" : "IGNORE EXISTING";
        return $"IMPORT \"{schema}\".\"*\" AS BINARY FROM '{importDir}' WITH {opts} THREADS {threads};";
    }

    public static string ImportSchemaWithRename(
        string sourceSchema, string targetSchema, string importDir, int threads, bool replace)
    {
        var opts = replace ? "REPLACE" : "IGNORE EXISTING";
        return $"IMPORT \"{sourceSchema}\".\"*\" AS BINARY FROM '{importDir}' " +
               $"WITH {opts} RENAME SCHEMA \"{sourceSchema}\" TO \"{targetSchema}\" THREADS {threads};";
    }

    public static string DropSchema(string schema)
        => $"DROP SCHEMA \"{schema}\" CASCADE";

    public static string RenameCompanyInCinf(string schema, string newName)
        => $"UPDATE \"{schema}\".CINF SET \"CompnyName\" = '{Escape(newName)}';";

    public static string RenameCompanyInOadm(string schema, string newName)
        => $"UPDATE \"{schema}\".OADM SET \"CompnyName\" = '{Escape(newName)}', \"PrintHeadr\" = '{Escape(newName)}';";

    public static string GetTenantName()
        => "SELECT DATABASE_NAME FROM SYS.M_DATABASES;";

    public static string BackupTenant(string backupPrefix)
        => $"BACKUP DATA USING FILE ('{backupPrefix}')";

    // SQL single-quote escape
    private static string Escape(string value) => value.Replace("'", "''");
}
