using System.Data.SqlClient;

namespace AdvertisingProfitControlData
{
    public class Restore
    {
        public string ErrorMessage = string.Empty;

        public bool SingleFileRestore(string databaseFilePath)
        {
            var sqlConStrBuilder = new SqlConnectionStringBuilder(AdvertisingProfitControlDbContext.ConnectionString);

            try
            {
                using (var conn = new SqlConnection(sqlConStrBuilder.ConnectionString))
                {
                    var query = $"RESTORE DATABASE {sqlConStrBuilder.InitialCatalog} FROM DISK='{databaseFilePath}'";

                    conn.Open();
                    var useMasterCommand = new SqlCommand("USE master", conn);
                    useMasterCommand.ExecuteNonQuery();
                    
                    var alter1Cmd = new SqlCommand($"ALTER DATABASE {sqlConStrBuilder.InitialCatalog} SET Single_User WITH Rollback Immediate", conn);
                    alter1Cmd.ExecuteNonQuery();

                    var restoreCmd = new SqlCommand(query, conn);
                    restoreCmd.ExecuteNonQuery();

                    var alter2Cmd = new SqlCommand($"ALTER DATABASE {sqlConStrBuilder.InitialCatalog} SET Multi_User", conn);
                    alter2Cmd.ExecuteNonQuery();
                    conn.Close();
                    return true;
                }
            }
            catch (SqlException e)
            {
                ErrorMessage = e.Message;
                return false;
            }
        }
    }
}
